Python中关于pyspider的post请求中data被转义导致无法抓取的问题

用 requests 请求时可以正常返回结果:
import requests
import json
headers = {
“Accept”: “/”,
“Accept-Encoding”: “gzip, deflate”,
“Accept-Language”: “zh-CN,zh;q=0.9”,
“Connection”: “keep-alive”,
“Content-Length”: “56”,
“Content-Type”: “application/json”,
“Host”: “www.bw30.com”,
“Origin”: “http://www.bw30.com”,
“Referer”: “http://www.bw30.com/”,
“User-Agent”: “Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36”,
}
data = json.dumps({“channeltype”: “shortvideo”, “tid”: 8, “index”: 0, “size”: 10})
a = requests.post(“http://www.bw30.com/videoserver/RPCACBCABF433DB30A893DC6C5863E3102C?tid=7”, data=data, headers=headers)
print(a.text)

同样的代码逻辑放到 pyspider 中则无法正常返回数据:
def on_start(self):
for tag, tid in {“美食”: 7, “资讯”: 8, “体育”: 10, “亲子”: 9, “微记录”: 11}.items():
url = “http://www.bw30.com/videoserver/RPCACBCABF433DB30A893DC6C5863E3102C?tid={}”.format(tid)
headers = {
“Accept”: “/”,
“Accept-Encoding”: “gzip, deflate”,
“Accept-Language”: “zh-CN,zh;q=0.9”,
“Connection”: “keep-alive”,
“Content-Length”: “56”,
“Content-Type”: “application/json”,
“Host”: “www.bw30.com”,
“Origin”: “http://www.bw30.com”,
“Referer”: “http://www.bw30.com/”,
“User-Agent”: “Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36”,
}
data = {“channeltype”: “shortvideo”, “tid”: tid, “index”: 0, “size”: 10}
data = str(data)
self.crawl(url, callback=self.index_page,save={‘column_name’:tag},method=“POST”,data=data, headers=headers)
Python中关于pyspider的post请求中data被转义导致无法抓取的问题


4 回复

emmmm, 有没有大佬协助一下, 我在网上搜过之后, 只有提问的, 没有解答的。。


我遇到过这个问题,pyspider的post请求中data被转义确实很烦人。核心原因是pyspider的HTTP请求库在处理data参数时,如果传入的是字符串,会自动进行URL编码,但有时候服务器需要的是原始JSON数据。

解决方案:

  1. 使用json参数(推荐) - 这是最简单直接的方法:
import json

def on_start(self):
    self.crawl('http://example.com/api',
               method='POST',
               json={'key': 'value', 'data': [1, 2, 3]},  # 自动设置Content-Type为application/json
               callback=self.parse)
  1. 手动设置headers和data - 当需要更多控制时:
def on_start(self):
    import json
    data = json.dumps({'key': 'value', 'data': [1, 2, 3]})
    self.crawl('http://example.com/api',
               method='POST',
               data=data,
               headers={'Content-Type': 'application/json'},
               callback=self.parse)
  1. 使用files参数 - 对于multipart/form-data:
def on_start(self):
    self.crawl('http://example.com/upload',
               method='POST',
               files={'file': ('filename.txt', 'file content')},
               callback=self.parse)

关键点:

  • 如果服务器期望JSON,就用json参数
  • 如果服务器期望表单数据,就用data参数(字典形式)
  • 避免将字典转为字符串后传给data参数,这会导致双重编码

我通常先用json参数,不行再试手动设置headers的方式。

data 不用转 str 的吧? 多看看文档

原网站的 data 是需要转的,一般转不转 str 取决于原网站对于 data 的封装方式。同样的代码在 python 下是可以走通的,可是在 pyspider 里边就会请求失败。

回到顶部