在python獲取網頁的代碼中添加頭信息模擬瀏覽器


方法1:使用build_opener()來添加

import urllib2
url = "https://www.baidu.com"
headers = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
opener = urllib2.build_opener()
opener.addheaders = [headers]
file = opener.open(url)
html = file.read()
print html

方法2:利用add_header()來添加

import urllib2
url = "https://blog.51cto.com/lsfandlinux/2046467"
req = urllib2.Request(url)
req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
file = urllib2.urlopen(req)
html = file.read()
print html

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM