python爬蟲-基礎入門-爬取整個網站《2》
阿新 • • 發佈:2018-11-04
python爬蟲-基礎入門-爬取整個網站《2》
描述:
開場白已在《python爬蟲-基礎入門-爬取整個網站《1》》中描述過了,這裡不在描述,只附上 python3 的程式碼。
python3 指令碼程式碼:
1 #-*- coding: utf-8 -*- 2 3 import urllib.request 4 5 6 def baiduNet() : 7 8 response = urllib.request.urlopen("http://www.baidu.com") 9 netcontext = response.read().decode("utf-8") 10 11 file = open("baidutext.txt", "w", encoding='UTF-8') 12 file.write(netcontext) 13 14 if __name__ == "__main__" : 15 baiduNet()
注意:
在python3中包urllib2歸入了urllib中,所以要匯入urllib.request,並且要把urllib2替換成urllib.request
urlopen方法
>> 獲取頁面資訊
>> 語法形式
urllib.request.urlopen(url, data=None, [timeout])
-> url : 需要開啟的網址
-> data : post需要提交的資料
-> timeout : 設定網站的訪問超市時間
>> 結果:
response = urllib.request.urlopen("http://www.baidu.com")
netcontext = response.read().decode("utf-8")
使用read()方法讀取響應物件中的文字,注意:得到文字資料格式為byte型別,需要decode()方法解碼,轉換成string型別。
--->>> 擴充套件,urlopen其它方法
方法 | 功能 |
read(),readline(),readlines(),fileno(),close() | 對HHTTPResponse型別資料進行操作 |
info() | 返回HTTPMessage物件,表示遠端伺服器返回的頭資訊 |
getcode() | 返回Http狀態碼,如果是http請求,200請求成功狀態碼;404網址未找到 |
geturl() | 返回請求的url |
如有問題,歡迎糾正!!!
如有轉載,請標明源處:https://www.cnblogs.com/Charles-Yuan/p/9903242.html