urllib发送get请求_中文传参问题

GET请求是HTTP协议中的一种基本方法,当需要在GET请求中传递中文参数时需要额外对中文进行编码(英文不需要),因为url中只能包含ascii字符。

可以使用urllib.parser.urlencode()或urllib.parse.quote()方法对中文转码。

详细查官方文档: https://docs.python.org/3.12/library/urllib.parse.html#module-urllib.parse

查看使用百度搜索“python爬虫”时,url会传递哪些参数

传递参数以“?”开始,由“&”分割。其中“python爬虫”传递给了“wd”。

浏览器将中文转换为url编码

直接使用中文传参会报错

对wd直接传中文参数
from urllib.request import urlopen, Request
# 请求地址
url = 'https://www.baidu.com/s?wd=python爬虫'
# 创建Request对象
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36'}
req = Request(url, headers=headers)
# 发送请求
resp = urlopen(req)
# 读取响应内容
print(resp.read().decode())
# 关闭连接
resp.close()

 

部分报错信息为:

UnicodeEncodeError: 'ascii' codec can't encode characters

修改上述代码url = 'https://www.baidu.com/s?wd=python%E7%88%AC%E8%99%AB'可以执行成功

使用python的urllib库对中文编码

urllib.parse.quote()

from urllib.parse import quote
# urllib.parse.quote()转换一个值
args = 'python爬虫'
print(quote(args))
'''
运行结果:
python%E7%88%AC%E8%99%AB
'''

urllib.parse.urlencode()

from urllib.parse import urlencode
# urllib.parse.urlencode() 转换键值对
args = {'wd': 'python爬虫'}
print(urlencode(args))
'''
运行结果:
wd=python%E7%88%AC%E8%99%AB
'''

两种方法实现含中文传参的GET请求

from urllib.request import Request, urlopen
from urllib.parse import quote, urlencode
# 请求地址
args1 = 'python爬虫' # 方法一,使用urllib.parse.quote()
# 方法二,使用urllib.parse.urlencode()
# args2 = {'wd': 'python爬虫'}
url = f'https://www.baidu.com/s?wd={quote(args1)}' 
# url = f'https://www.baidu.com/s?{urlencode(args2)}'
# 创建Request对象
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36'}
req = Request(url, headers=headers)
# 发送请求
resp = urlopen(req)
# 获取响应码
print(resp.getcode())
# 关闭连接
resp.close()

响应码为200即请求成功。

posted @ 2024-09-12 22:45  松鼠q  阅读(13)  评论(0编辑  收藏  举报