浏览器伪装

#浏览器伪装
import urllib.request
import urllib.error
import random
#头文件格式header=("User=Agent",具体用户代理值)
my_hearders=[
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14",  
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)"
]
random_header=random.choice(my_hearders)

hearder=("User-Agent",random_header)
url="https://news.dahe.cn/2019/06-07/495218.html"

opener=urllib.request.build_opener()
opener.addheaders=[hearder]

file=open("C:\\Users\\gaoxingyuan\\Desktop\\myip.html","wb")

try:
    
    data=opener.open(url).read()
    
except urllib.error.URLError as e:
    
    if hasattr(e,"code"):
        print(e.code)
    if hasattr(e,"reason"):
        print(e.reason)
        
file.write(data)
file.close()

你可能感兴趣的:(python笔记)