Python 爬虫 (requests) 发送中文编码的 HTT
2018-05-20 本文已影响0人
liaozb1996
向往常一样发送POST请求出现错误
网站信息



使用 requests 发送 post 请求
In [2]: import requests
In [3]: from bs4 import BeautifulSoup as BS
In [4]: url = 'http://example.com/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 发送的数据


可以看到 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