1. 程式人生 > 其它 >【Python學習筆記】爬蟲基礎(獲取網頁資訊)

【Python學習筆記】爬蟲基礎(獲取網頁資訊)

前往:我自己搭建的部落格

所用版本:Python 3.6

利用urllib.request.urlopen()獲取指定網頁的原始碼,並存入一個物件中。用這個物件的read()和decode()方法進行讀取和解碼。urllib.request.urlopen()預設獲取一個get請求的響應,如果使用data引數,則為post請求。為了應對某些網站的反爬機制,需要程式偽裝成真實使用者,封裝一個請求物件。

# -*- coding: utf-8 -*-
import urllib.request
import urllib.parse

#獲取一個get請求的響應
response=urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8")) #獲取網頁內容
print(response.status) #獲取狀態碼
print(response.getheaders()) #獲取請求的頭部資訊
print(response.getheader('Server')) #獲取頭部資訊中的某個特定值

#處理網頁超時,程式卡死的情況
try:
    response=urllib.request.urlopen("http://www.baidu.com",timeout=3)
except urllib.error.URLError as e:
    print("time out")

#獲取一個post請求的響應
data=bytes(urllib.parse.urlencode({"name":"Martin"}),encoding="utf-8")
response=urllib.request.urlopen("http://httpbin.org/post",data=data)

#偽裝成真實使用者
url="https://www.douban.com"
headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"}
request=urllib.request.Request(url=url,headers=headers)
response=urllib.request.urlopen(request)