1. 程式人生 > >模擬瀏覽器——Headers屬性

模擬瀏覽器——Headers屬性

html blog rom build csdn .cn 瀏覽器 wow request

方法一、使用build_opener()修改報頭

1 import urllib.request
2 url = "https://www.cnblogs.com"
3 headers = (
4     "User-Agent",
5     "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"
6            )
7 opener = urllib.request.build_opener()
8 opener.addheaders = [headers]
9 data = opener.open(url).read()

方法二、使用add_header()添加報頭

import urllib.request
url = "http://blog.csdn.net/column.html"
req = urllib.request.Request(url)
req.add_header(
"User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"
) data
= urllib.request.urlopen(req).read()

模擬瀏覽器——Headers屬性