1. 程式人生 > >python 爬蟲(一)urllib使用demo

python 爬蟲(一)urllib使用demo

import urllib.request

#向指定的url地址發起請求,並返回伺服器響應的資料(檔案的物件)
response = urllib.request.urlopen("http://www.baidu.com")


#直接將檔案寫入指定路徑,
filePath = r"C:/Users/zyy/PycharmProjects/untitled/爬蟲/mile1.html"
response2 = urllib.request.urlretrieve(r"http://www.baidu.com",filePath)
urllib.request.urlcleanup() #清除快取


'''
1)讀取檔案的全部內容
data = response.read()
'''

'''
2)讀取一行,需要迴圈讀取
data = response.readline()
'''

'''
3)讀取所有行,並把讀取到的資料賦值給一個列表變數  -->建議使用
data列表的每一條都是
data = response.readlines()
for dd in data:
    str = dd.decode("utf-8")  #將bytes位元組轉換成字串
'''

'''
response的常用方法
1)response.info()
返回當前環境有關資訊

2)response.getcode()
返回狀態碼
200     -->訪問成功
304     -->客戶已經執行了GET,但檔案未變化(快取)
404     -->網頁不存在/url出錯
500     -->伺服器出現問題

3)response.geturl()
返回當前正在爬取的url地址
'''
data = response.readlines()
for dd in data:
    str = dd.decode("utf-8")
print(response.geturl())

filePath就是你想要儲存爬取到的網頁檔案,最好是儲存到html檔案中,這個檔案地址不存在的話程式會自動生成