在scrapy 发送post请求的时候,通常使用百度搜索,例子最多的是使用FormRequest
大概如下:
yield scrapy.FormRequest(url=account_info_url, cookies=cookie, body=json.dumps(params),method='POST', meta={'from_account': agency_name,'cookies': cookie},
callback=self.parse, dont_filter=True
这里简单做下说明,cookie 的 格式在scrapy里面为字典格式,body格式为字符串;使用FormRequest 还需要在请求头中设置正确的'content-type':
如下:
headers = {
'accept': 'application/json, text/javascript, */*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'content-type': 'application/json; charset=UTF-8',
'origin': 'https://ad.qq.com',
'referer': 'https://ad.qq.com/worktable/?source_uri=https%3A%2F%2Fad.qq.com%2F',
'sec-fetch-mode': 'cors',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
}
下面介绍一种简单发送post请求的方法----JsonRequest,
主要源码如下(和Frome一样 都继承与Request):
在使用的时候和FromRequest的使用方法基本相同(直接使用yield scrapy.http.JsonRequest),但是它不需要在源码中设置content-type(源码中已经设置了默认的content-type)。
yield scrapy.FormRequest(url=account_info_url, cookies=cookie, body=json.dumps(params),method='POST',
yield scrapy.http.JsonRequest(url=account_info_url, cookies=cookie, body=json.dumps(params), method='POST',
meta={'from_account': agency_name,'cookies': cookie},
callback=self.parse, dont_filter=True
结果如下:
使用FromRequest:
使用scrapy.http.JsonRequest
注释掉请求头中content-type