![](/img/trans.png)
[英]Why this simple POST request not working in Python Scrapy whereas it works with simple request.post()
[英]Python request.post() not working when converted to Python Scrapy Request
我有簡單的POST請求代碼。
headers = {
dictionary of headers
}
params = (
('param1', '0'),
('param2', '5668294380'),
('param3', '8347915011'),
)
response = requests.post('https://website.com', headers=headers, params=params, data=__data)
這完全可以作為獨立的Python程序使用。
但是我想在Python Scrapy中做到這一點
Request(url='https://website.com',callback=self.callback_fun, headers=headers, body=__data, method="POST")
它給我的回應是URL無法處理POST請求
我試過了
FormRequest(url='https://website.com',callback=self.callback_fun, headers=headers, body=__data)
它給了我同樣的回應。
我試過了
Request(url='https://website.com?' + urllib.urlencode(self.params),callback=self.callback_fun, headers=headers, body=__data, method="POST")
但這給了我400 Bad Request
Scrapy怎么了? 我的意思是純Python腳本有效,但在Scrapy中不起作用。
我認為主要問題是如何使用Scrapy發送params=params
。 Scrapy僅允許通過body
參數發送請求有效負載
class scrapy.http.FormRequest(url[, formdata, ...])
參數:formdata(元組的dict或可迭代)–是一個字典(或元組(鍵,值)可迭代),其中包含HTML表單數據,該數據將被url編碼並分配給請求的主體。
在HTTP中,如果要發布數據,則將數據設置在請求正文中並進行編碼。 您可以編碼自己的字典,也可以使用Scrapy FormRequest
:
class FormRequest(Request):
def __init__(self, *args, **kwargs):
formdata = kwargs.pop('formdata', None)
if formdata and kwargs.get('method') is None:
kwargs['method'] = 'POST'
super(FormRequest, self).__init__(*args, **kwargs)
if formdata:
items = formdata.items() if isinstance(formdata, dict) else formdata
# encode dict here
querystr = _urlencode(items, self.encoding)
if self.method == 'POST':
# set message header
self.headers.setdefault(b'Content-Type', b'application/x-www-form-urlencoded')
# set message body
self._set_body(querystr)
else:
self._set_url(self.url + ('&' if '?' in self.url else '?') + querystr)
----------------------------更新--------------
在請求代碼中:
response = requests.post('https://website.com', headers=headers, params=params, data=__data)
它首先將參數添加到URL,將發布數據添加到修改后的URL。 您應該更改您的URL。 您可以通過以下方式獲取網址:
print(response.url)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.