開發與維運

Python實現urllib3和requests庫使用 | python爬蟲實戰之五

python爬蟲AJAX數據爬取和HTTPS訪問 | python爬蟲實戰之四

urllib3庫

https://urllib3.readthedocs.io/en/latest/
標準庫urllib缺少了一些關鍵的功能, 非標準庫的第三方庫urllib3提供了, 比如說連接池管理。

安裝

$ pip install urllib3

之後,我們來借用之前的json數據來看一下:

import urllib3
from urllib.parse import urlencode
from urllib3.response import HTTPResponse

jurl = 'https://movie.douban.com/j/search_subjects'

d = {
    'type':'movie',
    'tag':'熱門',
    'page_limit':10,
    'page_start':10
}

with urllib3.PoolManager as http:
  #  http.urlopen()
     response = http.request('GET', '{}?{}'.format(jurl, urlencode(d)), headers={
    'User-agent': "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36"
    })
    print(type(response))
    # response:HTTPResponse = HTTPResponse()
    print(response.status)
    print(response.data)

執行結果:

image.png

image.png

這個封裝的屬性和方法還是比較原始的,我們對於這樣的使用肯定是不行的,那我們需要用什麼呢?接著來講requests庫。

requests庫

requests使用了urllib3, 但是API更加友好, 推薦使用。
需要先安裝,跟之前一樣。
安裝:

$ pip install requests

我們對上面的例子做出修改:

import urllib3
from urllib.parse import urlencode
from urllib3.response import HTTPResponse

import requests

jurl = 'https://movie.douban.com/j/search_subjects'

d = {
    'type':'movie',
    'tag':'熱門',
    'page_limit':10,
    'page_start':10
}


url = '{}?{}'.format(jurl, urlencode(d))

response = requests.request('GET', url, headers = {
    'User-agent': "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36"
})


with response:
    print(response.text)
    print(response.status_code)
    print(response.url)
    print(response.headers)
    print(response.request)

執行結果:

image.png

我們具體來看一下request:

    print(response.headers, '~~~~~')
    print(response.request.headers)

上面的headers是response的,下面的是請求的headers
執行結果:

image.png

裡面還有別的參數,大家可以去嘗試一下。

image.png

requests默認使用Session對象, 是為了在多次和服務器端交互中保留會話的信息, 例如cookie。

直接使用Session:

image.png
image.png

我們也來嘗試去打印一下這些信息:

import requests

urls = ['https://www.baidu.com/s?wd=magedu', 'https://www.baidu.com/s?wd=magedu']
session = request.session()
with session:
    for url in urls:
        response = session.get(url, headers = {
        'User-agent': "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36"
        })
    
        with response:
            print(response.text[:50])
            print('-'*30)
            print(response.cookies)
            print('-'*30)
            print(response.headers, '~~~~~')
            print(response.request.headers)

執行結果:

image.png
image.png
image.png

通過結果可以看出,Session對象對cookie起了作用。觀察第一次返回的cookie與第二次發起請求的response.request.headers的cookie。返回的結果依然是鍵值對,只是之中value的值依然是用鍵值對來表示的。

配套視頻課程,點擊這裡查看

獲取更多資源請訂閱Python學習站

Leave a Reply

Your email address will not be published. Required fields are marked *