urllib.request.urlopen()与urllib.request.Request()

使用urllib.request.urlopen()与urllib.request.Request() 获得响应

import urllib.request
r = urllib.request.urlopen('https://gzdaily.dayoo.com/pc/html/2020-08/04/content_132879_713872.htm')
html = r.read().decode('utf-8')
print(html)

这便是一个简单向网站发请求的框架,这种时候经常遇到反爬,比如使用它向百度网页发一个请求,便会遇到反扒~~
这时,可以考虑使用urllib.request.Request()____原因在于它可以方便的添加反爬技术heades等操作:

import urllib.request
url = 'https://www.baidu.com/'
headers = {
     'User-Agent':'''Mozilla/5.0 
(Windows NT 10.0; Win64; x64) AppleWebKit/537.36
 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'''}
r = urllib.request.Request(url,headers=headers)
#向网页发请求
res = urllib.request.urlopen((r))
#使字节流  转化为  字符串
html = res.read().decode('utf-8')
#获得  返回状态码
print(res.getcode())
#获得  实际请求网站
print(res.geturl())

总结:urllib.request.urlopen()不能直接添加headers,若要添加则需使用urllib.request.Request().

你可能感兴趣的:(框架,格式书写,python)