爬虫_urllib的请求
1.get请求的quote方法
quote()方法:是将汉字转换成unicode编码
import urllib.request import urllib.parse url = 'https://www.baidu.com/s?wd=' #请求对象的定制是为了解决反爬的第一种手段 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36' } #将“周杰伦”三个汉字变成unicode编码的格式 #需要依赖urllib.parse name = urllib.parse.quote('周杰伦') #拼接请求的新url url = url+name #请求对象的定制 request = urllib.request.Request(url=url,headers=headers) #模拟浏览器向服务器发送请求 response = urllib.request.urlopen(request) #获取响应的内容 content = response.read().decode('utf-8') #打印数据 print(content)
2.urlencode方法
import urllib.request import urllib.parse base_url = 'https://www.baidu.com' data = { 'wd':'周杰伦', 'sex':'男', 'location':'中国台湾省' } new_data = urllib.parse.urlencode(data) # 请求资源路径 url = base_url + new_data headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36' } # 请求对象的定制 request = urllib.request.Request(url = url,headers= headers) # 模拟浏览器向服务器发送请求 response = urllib.request.urlopen(request) #获取网页源码的数据 content = response.read().decode('utf-8') #打印数据 print(content)
3.post请求
#post 百度翻译 import urllib.request import urllib.parse import json #第一步:请求地址 url = 'https://fanyi.baidu.com/sug' #第二步:请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36' } #第三步:请求参数 data = { 'kw':'spider' } #post请求的参数必须要进行编码 data = urllib.parse.urlencode(data).encode('utf-8') #第四步:请求对象定制 #post的请求的参数是不会拼接在url的后面的,而是需要放在请求对象定制的参数中 request = urllib.request.Request(url=url,data=data,headers=headers) #第五步:模拟浏览器向服务器发送请求 response = urllib.request.urlopen(request) #第六步:获取响应的数据 content = response.read().decode('utf-8') #将字符串转换成为json对象 obj = json.loads(content) print(obj) #post请求的注意 #1) post 请求方式的参数必须编码, data = urllib.parse.urlencode(data) #2) 编码之后必须调用encode方法 #3) 参数是放在请求对象定制的方法中 data = urllib.parse.urlencode(data).encode('utf-8')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2021-05-20 easyui中datagrid 中添加编辑行的实现