爬蟲學習

入門:urllib庫學習

#從urllib中導入request
from urllib import request
#如果因爲是https需要ssl證書驗證發生錯誤的,需要導入ssl庫以及下面的代碼
import ssl
ssl._create_default_https_context = ssl._create_default_https_context

url = ‘http://www.baidu.com’
#使用urlopen爬取網頁
headers = {
‘User-Agent’:‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36’
}
resp = request.urlopen(url)
#resp.read()閱讀到的是編碼過的內容,需要decode()對中文及符號進行解碼才能看懂
print(resp.read().decode())

#urlretrieve直接保存爬取到的url內容
request.urlretrieve(url,‘baidu.html’)

#代理實現
#1、使用proxyhandler傳入代理,構建一個handler
#可以從一些免費的代理網站找代理,例如快代理等
handler = request.ProxyHandler({‘http’:‘106.14.58.95:8083’})
#2、使用handler構建一個opener,其實urlopen底層調用的也是opener的方法
opener = request.build_opener(handler)
#3、使用opener去發送請求,這個相當於就是urlopen的底層
resp = opener.open(url)
print(resp.read().decode())

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章