天天看點

Python爬蟲——urllib的使用

Python爬蟲——urllib的使用

本文使用的版本為Python3,使用的IDE為Pycharm
  • 爬取百度首頁
# 導入子產品
from urllib import request

# 僞裝成浏覽器
headers=("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36")
opener=request.build_opener()
opener.addheaders=[headers]
request.install_opener(opener)

# 設定逾時
file = request.urlopen("http://www.baidu.com", timeout=)
# 讀取全部資料
data = file.read()
# 讀取第一行資料
dataline = file.readline()
# 寫入檔案
fhandle = open("D:/baidu.html", "wb")
fhandle.write(data)
fhandle.close()

print(dataline)
print(data)