import urllib.request
url = 'https://www.baidu.com'
# url的组成
# http/https www.baidu.com 80 / 443
# 协议 主机 端口号 路径 参数 锚点
# http 80
# https 443
#请求头,能够在浏览器里面检查的network找到
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
}
#因为 urlopen方法中不能存储字典, 所以headers不能传递进去
#请求对象的定制
# 注意 因为参数的顺序问题 不能直接写url 和 headers 中间还有data 所以我们需要关键字传参
#请求参数
request = urllib.request.Request(url=url, headers=headers)
#响应数据
response = urllib.request.urlopen(request)
#传递数据,这里要注意的是,这里需要加上utf-8,要不然会乱码
content = response.read().decode('utf-8')
打印数据
print(content)
Python爬虫:urllib_请求对象的定制(03)
于 2024-10-21 09:34:22 首次发布
1452

被折叠的 条评论
为什么被折叠?



