爬蟲之urllib庫

2021-08-18 16:43:21 字數 1393 閱讀 5161

一、urllib的基本使用

import urllib.request

response=urllib.request.urlopen('')

#獲取當前爬取網頁的狀態碼

print(response.getcode())

#decode():解碼  位元組資料轉成字串資料

# #data=response.read().decode('utf-8')

# data=response.read()

# print(data)

#寫入位元組流形式資料時,模式要用wb

# fandle=open('1.html','wb')

# fandle.write(data)

# fandle.close()

#-->如果將爬取到的網頁以網頁的形式儲存在本地

# 方法一:

# 1》爬取乙個網頁將爬取到的內容讀取出來賦給乙個變數

# 2》以寫入的方式開啟乙個本地檔案,命名***.html網頁格式

# 3》將1》得到的變數值寫入該檔案中

# 4》關閉檔案

# 方法二:

#urlretrieve()函式直接將對應資訊寫入本地檔案

# filename=urllib.request.urlretrieve('',filename='2.html')

二、urllib設定headers

fhandle.close()

方法二:

fhandle.close()

三、設定超時

import urllib.request

for i in range(1,50):

try:

file=urllib.request.urlopen('',timeout=0.5)

data=file.read()

print(len(data))

except exception as e:

print('出現異常-->'+str(e))

四、get請求和post請求

get:

# import urllib.request

keyword='hello'

#2.構建url

url='/s?wd='+keyword

#3.建立乙個request()物件

req=urllib.request.request(url)

#4.獲取響應內容

data=urllib.request.urlopen(req).read()

#5.資料儲存

fhandle=open('5.html','wb')

fhandle.write(data)

fhandle.close()

post:

fd.close()

爬蟲庫之urllib

官方文件 utllib是python內建的http請求庫 包含一下模組 相比與python的變化 python2 import urllib2 response urllib2.urlopen python3 import urlib.request response urllib.request....

Python 爬蟲乾貨之urllib庫

小試牛刀 怎樣扒網頁呢?其實就是根據url來獲取它的網頁資訊,雖然我們在瀏覽器中看到的是一幅幅優美的畫面,但是其實是由瀏覽器解釋才呈現出來的,實質它是一段html 加 js css,如果把網頁比作乙個人,那麼html便是他的骨架,js便是他的肌肉,css便是它的衣服。所以最重要的部分是存在於html...

爬蟲基礎 urllib庫

使用 urllib 匯入必要模組 from urllib import request 如果需要 url轉碼 from urllib import parse print parse.quote 范冰冰 e8 8c 83 e5 86 b0 e5 86 b0 urlopen url rsp reque...