LOADING

加载过慢请开启缓存 浏览器默认开启

urllib库(4)请求对象的定制

2023/11/6

一个url的组成

示例:https://www.baidu.com/s?wd=%E5%91%A8%E6%9D%B0%E4%BC%A6&sex=%E7%94%B7&location=%E4%B8%AD%E5%9B%BD%E5%8F%B0%E6%B9%BE%E7%9C%81
1、协议:http/https
2、主机:www.baidu.com
3、端口号:
http:80
https:443
mysql:3306
oracle:1521
redis:6379
mongodb:27107
4、路径:s
5、参数:问号之后的数据
6、锚点

http和https协议的区别

https经过加密,如果直接用urlopen函数打开使用https协议的url,那么获取到的数据就是不完整的

用户代理

User-Agent:一个反爬虫,放在一个名为headers的字典中

headers包含了很多参数,例如Accept,Cookie等,但是最重要的参数还是Cookie!

请求对象的定制

函数urlopen的传参URL可以是一个字符串表示的url,也可以是一个request类型的对象

把url和headers传入,获得一个request类型的对象,然后再传入urlopen函数中去获得响应

特别注意:这里定制request对象必须用关键字传参!因为url和headers中间还有一个data传参,因此不能使用顺序传参!

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/117.0.0.0 Safari/537.36'
}


request = urllib.request.Request(url = url,headers = headers)

response = urllib.request.urlopen(request)
content = response.read().decode("utf-8")
print(content)