urllib.request headers 兩種方法和注意問題
阿新 • • 發佈:2018-12-12
url= "http://desk.zol.com.cn/"
#第一種個人覺得好用方便
req = urllib.request.Request(url)
req.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36")
#req.add_header() 要注意不是headers
print(req.headers)
#這樣就會返回剛設定的headers
#第二種 url= "http://desk.zol.com.cn/" head = {} head['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' #把hedaers 做為一個定典 req = urllib.request.Request(url,headers = head) print(req.headers) #這樣也會返回headers