浙江11选5走图:Python核心??櫓畊rllib用法詳解【Python每日一個知識點第79期】

浙江11选5任3遗漏 www.ehxis.com urllib是Python內建的核心??櫓?,主要用于各種網頁請求的構造。這個??椴僮鞣淺<虻?,而且功能比較強大,是爬蟲入門的不二之選。今天我們為大家整理了urllib庫的一些核心用法,幫助大家更快的掌握其用法。Python爬蟲項目中常用的requests庫即時基于urllib構建的。


Get

urllib的request??榭梢苑淺7獎愕刈トRL內容,也就是發送一個GET請求到指定的頁面,然后返回HTTP的響應:

例如,對豆瓣的一個URLhttps://api.douban.com/v2/book/2129650進行抓取,并返回響應:

from urllib import request

with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
    data = f.read()
    print('Status:', f.status, f.reason)
    for k, v in f.getheaders():
        print('%s: %s' % (k, v))
    print('Data:', data.decode('utf-8'))

可以看到HTTP響應的頭和JSON數據:

Status: 200 OK
Server: nginx
Date: Tue, 26 May 2015 10:02:27 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2049
Connection: close
Expires: Sun, 1 Jan 2006 01:00:00 GMT
Pragma: no-cache
Cache-Control: must-revalidate, no-cache, private
X-DAE-Node: pidl1
Data: {"rating":{"max":10,"numRaters":16,"average":"7.4","min":0},"subtitle":"","author":["廖雪峰編著"],"pubdate":"2007-6",...}

如果我們要想模擬瀏覽器發送GET請求,就需要使用Request對象,通過往Request對象添加HTTP頭,我們就可以把請求偽裝成瀏覽器。例如,模擬iPhone 6去請求豆瓣首頁:

from urllib import request

req = request.Request('//www.douban.com/')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
with request.urlopen(req) as f:
    print('Status:', f.status, f.reason)
    for k, v in f.getheaders():
        print('%s: %s' % (k, v))
    print('Data:', f.read().decode('utf-8'))

這樣豆瓣會返回適合iPhone的移動版網頁:

...
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="format-detection" content="telephone=no">
    <link rel="apple-touch-icon" sizes="57x57" href="//img4.douban.com/pics/cardkit/launcher/57.png" />
...

Post

如果要以POST發送一個請求,只需要把參數data以bytes形式傳入。

我們模擬一個微博登錄,先讀取登錄的郵箱和口令,然后按照weibo.cn的登錄頁的格式以username=xxx&password=xxx的編碼傳入:

from urllib import request, parse

print('Login to weibo.cn...')
email = input('Email: ')
passwd = input('Password: ')
login_data = parse.urlencode([
    ('username', email),
    ('password', passwd),
    ('entry', 'mweibo'),
    ('client_id', ''),
    ('savestate', '1'),
    ('ec', ''),
    ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
])

req = request.Request('https://passport.weibo.cn/sso/login')
req.add_header('Origin', 'https://passport.weibo.cn')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')

with request.urlopen(req, data=login_data.encode('utf-8')) as f:
    print('Status:', f.status, f.reason)
    for k, v in f.getheaders():
        print('%s: %s' % (k, v))
    print('Data:', f.read().decode('utf-8'))

如果登錄成功,我們獲得的響應如下:

Status: 200 OK
Server: nginx/1.2.0
...
Set-Cookie: SSOLoginState=1432620126; path=/; domain=weibo.cn
...
Data: {"retcode":20000000,"msg":"","data":{...,"uid":"1658384301"}}

如果登錄失敗,我們獲得的響應如下:

...
Data: {"retcode":50011015,"msg":"\u7528\u6237\u540d\u6216\u5bc6\u7801\u9519\u8bef","data":{"username":"[email protected]","errline":536}}

Handler

如果還需要更復雜的控制,比如通過一個Proxy去訪問網站,我們需要利用ProxyHandler來處理,示例代碼如下:

proxy_handler = urllib.request.ProxyHandler({'http': '//www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
with opener.open('//www.example.com/login.html') as f:
    pass

小結

urllib提供的功能就是利用程序去執行各種HTTP請求。如果要模擬瀏覽器完成特定功能,需要把請求偽裝成瀏覽器。偽裝的方法是先監控瀏覽器發出的請求,再根據瀏覽器的請求頭來偽裝,User-Agent頭就是用來標識瀏覽器的。


《Python入門每日一個知識點》欄目是馬哥教育Python年薪20萬+的學員社群特別發起,分享Python工具、Python語法、Python項目等知識點,幫助大家快速的了解Python學習,快速步入Python高薪的快車道。

【超全整理】《Python自動化全能開發從入門到精通》python基礎教程筆記全放送

相關新聞

聯系我們

400-080-6560

在線咨詢:點擊這里給我發消息

郵件:[email protected]

工作時間:周一至周日,09:00-18:30

QR code