自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一篇文章帶你搞定Python中urllib庫(操作URL)

開發(fā) 后端
使用Python語言,能夠幫助大家更好的學(xué)習(xí)Python。urllib提供的功能就是利用程序去執(zhí)行各種HTTP請求。如果要模擬瀏覽器完成特定功能,需要把請求偽裝成瀏覽器。

[[434848]]

Hey,大家好呀,我是Go進(jìn)階者。

一、操作URL

urllib提供了一系列用于操作URL的功能。分類講解相關(guān)內(nèi)容。

二、Get()

urllib的request模塊可以非常方便地抓取URL內(nèi)容,也就是發(fā)送一個(gè)GET請求到指定的頁面,然后返回HTTP的響應(yīng):

例如,對豆瓣的URLhttps://api.growingio.com/v2/22c937bbd8ebd703f2d8e9445f7dfd03/web/pv?stm=1593747087078進(jìn)行抓取,并返回響應(yīng):

  1. from urllib import request 
  2.  
  3. with request.urlopen('https://api.growingio.com/v2/22c937bbd8ebd703f2d8e9445f7dfd03/web/pv?stm=1593747087078'as f: 
  4.     data = f.read() 
  5.     print('Status:', f.status, f.reason) 
  6.     for k, v in f.getheaders(): 
  7.         print('%s: %s' % (k, v)) 
  8.     print('Data:', data.decode('utf-8')) 

可以看到HTTP響應(yīng)的頭和JSON數(shù)據(jù):

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

  1. from urllib import request 
  2.  
  3. req = request.Request('http://www.douban.com/'
  4. 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'
  5. with request.urlopen(req) as f: 
  6.     print('Status:', f.status, f.reason) 
  7.     for k, v in f.getheaders(): 
  8.         print('%s: %s' % (k, v)) 
  9.     print('Data:', f.read().decode('utf-8')) 

這樣豆瓣會返回適合iPhone的移動版網(wǎng)頁:

三、Post()

如果要以POST發(fā)送一個(gè)請求,只需要把參數(shù)data以bytes形式傳入。

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

  1. from urllib import request, parse 
  2.  
  3. print('Login to weibo.cn...'
  4. #電子郵件 
  5. email = input('Email: '
  6. #密碼 
  7. passwd = input('Password: '
  8. #相關(guān)的參數(shù) 
  9. login_data = parse.urlencode([ 
  10.     ('username', email), 
  11.     ('password', passwd), 
  12.     ('entry''mweibo'), 
  13.     ('client_id'''), 
  14.     ('savestate''1'), 
  15.     ('ec'''), 
  16.     ('pagerefer''https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F'
  17. ]) 
  18. #網(wǎng)址請求 
  19. req = request.Request('https://passport.weibo.cn/sso/login'
  20. req.add_header('Origin''https://passport.weibo.cn'
  21. #構(gòu)造User-Agent 
  22. 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'
  23. req.add_header('Referer''https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F'
  24.  
  25. with request.urlopen(req, data=login_data.encode('utf-8')) as f: 
  26.     print('Status:', f.status, f.reason) 
  27.     for k, v in f.getheaders(): 
  28.         print('%s: %s' % (k, v)) 
  29.     print('Data:', f.read().decode('utf-8')) 

如果登錄成功,獲得的響應(yīng)如下:

如果登錄失敗,獲得的響應(yīng)如下:

四、Handler

如果還需要更復(fù)雜的控制,比如通過一個(gè)Proxy去訪問網(wǎng)站,需要利用ProxyHandler來處理,示例代碼如下:

  1. import urllib.request 
  2.  
  3. # 構(gòu)建了兩個(gè)代理Handler,一個(gè)有代理IP,一個(gè)沒有代理IP 
  4.  
  5. httpproxy_handler = urllib.request.ProxyHandler({"https""27.191.234.69:9999"}) 
  6.  
  7. nullproxy_handler = urllib.request.ProxyHandler({}) 
  8.  
  9. # 定義一個(gè)代理開關(guān) 
  10.  
  11. proxySwitch = True  
  12.  
  13. # 通過 urllib.request.build_opener()方法使用這些代理Handler對象,創(chuàng)建自定義opener對象 
  14.  
  15. # 根據(jù)代理開關(guān)是否打開,使用不同的代理模式 
  16.  
  17. if proxySwitch: 
  18.  
  19.     opener = urllib.request.build_opener(httpproxy_handler) 
  20. else
  21.     opener = urllib.request.build_opener(nullproxy_handler) 
  22.  
  23.  
  24. request = urllib.request.Request("http://www.baidu.com/")  
  25.  
  26. # 1. 如果這么寫,只有使用opener.open()方法發(fā)送請求才使用自定義的代理,而urlopen()則不使用自定義代理。 
  27.  
  28. response = opener.open(request) 
  29.  
  30. # 2. 如果這么寫,就是將opener應(yīng)用到全局,之后所有的,不管是opener.open()還是urlopen() 發(fā)送請求,都將使用自定義代理。 
  31.  
  32. # urllib.request.install_opener(opener) 
  33.  
  34. # response = urllib.request.urlopen(request) 
  35.  
  36.  
  37. # 獲取服務(wù)器響應(yīng)內(nèi)容 
  38.  
  39. html = response.read().decode("utf-8"
  40.    
  41. # 打印結(jié)果 
  42.  
  43. print(html) 

如果代理成功返回網(wǎng)址的信息。

如果網(wǎng)址出錯(cuò)或者代理地址有誤,返回下面界面。

五、總結(jié)

使用Python語言,能夠幫助大家更好的學(xué)習(xí)Python。urllib提供的功能就是利用程序去執(zhí)行各種HTTP請求。如果要模擬瀏覽器完成特定功能,需要把請求偽裝成瀏覽器。偽裝的方法是先監(jiān)控瀏j覽器發(fā)出的請求,再根據(jù)瀏覽器的請求頭來偽裝,User-Agent頭就是用來標(biāo)識瀏覽器的。

 

責(zé)任編輯:姜華 來源: Go語言進(jìn)階學(xué)習(xí)
相關(guān)推薦

2021-11-10 09:19:41

PythonShutil模塊

2021-11-17 10:11:08

PythonLogging模塊

2024-04-17 13:21:02

Python匿名函數(shù)

2021-05-15 10:16:14

Python匿名函數(shù)

2020-02-28 11:29:00

ElasticSear概念類比

2021-03-06 10:05:03

Python函數(shù)變量

2022-05-28 15:59:55

PythonPandas數(shù)據(jù)可視化

2021-02-20 10:06:14

語言文件操作

2021-01-13 08:40:04

Go語言文件操作

2021-05-31 08:59:57

Java數(shù)據(jù)庫訪問JDBC

2022-03-30 10:51:40

JavaScript性能調(diào)優(yōu)

2021-05-15 09:18:04

Python進(jìn)程

2021-03-15 08:38:42

StringBuffeJava基礎(chǔ)Java開發(fā)

2021-05-18 09:00:28

Pythonclass

2020-12-18 09:06:42

模塊Python系統(tǒng)

2022-02-21 09:44:45

Git開源分布式

2023-05-12 08:19:12

Netty程序框架

2021-06-30 00:20:12

Hangfire.NET平臺

2020-12-29 09:05:48

基礎(chǔ)DjangoORM

2021-01-05 09:07:30

Django ORMF查詢Q查詢
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號