import urllib.request
url="http://www.baidu.com"
headers=("user-agent")
opener= urllib.request.build_opener()
opener.addheaders=[headers]
data = opener.open(url).read()
方法二:使用add_header
import urllib.request
url= "http://www.baidu.com"
req=urllib.request.Request(url)
req.add_header('user-agent')
data=urllib.request.urlopen(req).read()
import urllib.request
for i in range(1,100):
try:
file = urllib.request.urlopen("http://www.baidu.com",timeout=30)
date = file.read()
print(len(data))
except Exception as e:
print("出现异常-->"+str(e))