900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > python request url编码_Python 爬虫 (requests) 发送中文编码的 HTTP POST 请求

python request url编码_Python 爬虫 (requests) 发送中文编码的 HTTP POST 请求

时间:2021-10-28 07:05:20

相关推荐

python request url编码_Python 爬虫 (requests) 发送中文编码的 HTTP POST 请求

向往常一样发送POST请求出现错误

网站信息

表单页面

结果

网页使用 gb2312 编码

使用 requests 发送 post 请求

In [2]: import requests

In [3]: from bs4 import BeautifulSoup as BS

In [4]: url = '/ip/search.asp'

In [5]: data = {

...: 'loudong': '女生九栋',

...: 'fangjian': '101-1'}

In [6]: res = requests.post(url, data=data)

In [9]: res.encoding = 'gb2312'

查询失败

使用 Wireshark 对比浏览器发送的数据和 requests 发送的数据

浏览器发送的 post 数据

requests 发送的 post 数据

可以看到 loudong 的值编码后不一样:

浏览器 使用 gb2312 进行编码

requests 使用 utf-8 进行编码

使用 requests 发送自己编码后的 post 请求

步骤:

为 HTTP Headers 手动加上 Content-Type: application/x-www-form-urlencoded

以字符串形式将编码后的 post 数据传给 requests 的 data 属性

如果表单处理的文本:enctype 的值是 application/x-www-form-urlencoded,也是默认值

如果表单处理的是提交文件:enctype 的值是 multipart/form-data

enctype 表示表单提交的数据的编码方式

如果将字典传给 requests 的 data 属性:requests 自动为数据进行编码

如果将字符串传给 requests 的 data 属性:requests 会直接发送字符串数据

In [12]: from urllib.parse import urlencode

# 对 post 数据进行 gb2312 编码

In [13]: data_gb2312 = urlencode(data, encoding='gb2312')

# 在 HTTP头部 添加 application/x-www-form-urlencoded

In [14]: headers = {

...: 'Content-Type': 'application/x-www-form-urlencoded'}

In [15]: res = requests.post(url, data=data_gb2312, headers=headers)

In [16]: res.encoding = 'gb2312'

In [17]: soup = BS(res.text, 'lxml')

In [18]: for item in soup.findAll('strong'):

...: print(item.parent.parent.text.replace('\n', ''))

...:

楼栋:女生九栋

房间号-端口号:101-1

IP地址:10.0.79.2

子网掩码:255.255.255.0

默认网关:10.0.79.1

首选DNS服务器:192.168.170.254

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。