Python之爬蟲基庫

一、request

  1. urlopen()函數的API
urllib. request. urlopen(url, data=None, [ t工『neout, ]*, cafile=None, capath=None, cadefault=False, context=None) 

1.data參數
data參數是可選的。如果要添加參數,並且如果它是字節流編碼格式的內容,即bytes類型,則需要通過bytes()方法轉化。請求方式不再是GET方式,而是POST方式。

import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word':'hello'}), encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())

2.timeout參數
timeout參數用於設置超時時間,單位爲秒,意思就是超過設置時間,沒有響應就會報錯。

import urllib.error
try:
    response = urllib.request.urlopen('http://www.baidu.com/get',timeout=1)
    print(response.read())
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT')
  1. Request
    request參數構造
class urllib. request. Request ( ur 1, data=None, headers={}, origin_req_host=None, unverifiable=False, method=N one) 

URL:用於請求URL,必傳參數
data:如果使用data,必須傳bytes類型。如果是字典,可以先用urllib.parse模塊裏的urlencode()編碼。
headers:請求頭,一般僞裝成瀏覽器
origin_req_host:請求方的host名稱或者IP地址。
unverifiable:表示這個請求是否無法驗證的,默認是false,換句話說用戶沒有足夠權限來選擇接受這個請求的結果。
method:用來請求使用的方法。比如GET,POST和PUT

from urllib import request,parse
url = 'http://httpbin.org/post'
headers = {
    'User-Agent':'Mozilla/4.0',
    'Host':'httpbin.org'
}
dict = {
    'name':'Germey'
}
data = bytes(parse.urlencode(dict),encoding='utf8')
req = request.Request(url=url,data=data,headers=headers,method='POST')
response=request.urlopen(req)
print(response.read().decode('utf-8'))

  1. 代理
from urllib.error import URLError
from urllib.request import ProxyHandler,build_opener
proxy_handler = ProxyHandler({
    'http':'http://127.0.0.1:9743',
    'https':'https:127.0.0.1:9743'
})
opener = build_opener(proxy_handler)
try:
    response = opener.open('https://www.baidu.com')
    print(response.read().decode('utf-8'))
except URLError as e:
    print(e.reason)
  1. Cookies
import http.cookiejar, urllib.request
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name+"="+item.value)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章