美文网首页
Scrapy和Requests的post请求详解

Scrapy和Requests的post请求详解

作者: 还是那个没头脑 | 来源:发表于2021-06-08 15:23 被阅读0次

1、scrapy框架发送post请求有两种格式

  • scrapy.FormRequest(url=url,formdata=formdata,cookies=self.cookie,headers=self.headers,callback=self.get_goods_list),这里的formdata是dict格式的,里面不能存在数字,如果有数字用引号括起来

  • scrapy.Request(url=url,method="POST",body=formdata,cookies=self.cookie,headers=self.headers,callback=self.get_goods_list),这里的formdata必须得是字符串,如果是表单格式,那么需要用json.dumps()转为字符串格式;

2、requests发送post请求,传递的参数也分两种格式(data和json)

  • requests.post(url, data=json.dumps(formdata)),这里面的data用的必须是字符串类型,如果formdata是一个表单(字典),那么用json.dumps(formdata)转化为字符串;

  • requests.post(url, json=formdata),这里面的formdata就必须是表单格式(字典),如果字典用format添加元素了,那么就会变成字符串,这时就需要用evel从字符串转化为字典(eval('{"orderby": "0","productTypeId": "%s","currentPage": "%s","pageSize": "12"}' %(id,i))),然后传递到data。

scrapy.Request()请求与requests.post()请求用法相同,得到的数据也是相同的

表单

from scrapy import FormRequest

首先,我们先看下FormRequest的部分源码:

class FormRequest(Request):
    valid_form_methods = ['GET', 'POST']

    def __init__(self, *args, **kwargs):
        formdata = kwargs.pop('formdata', None)
        if formdata and kwargs.get('method') is None:
            kwargs['method'] = 'POST'

        super().__init__(*args, **kwargs)

        if formdata:
            items = formdata.items() if isinstance(formdata, dict) else formdata
            querystr = _urlencode(items, self.encoding)
            if self.method == 'POST':
                self.headers.setdefault(b'Content-Type', b'application/x-www-form-urlencoded')
                self._set_body(querystr)
            else:
                self._set_url(self.url + ('&' if '?' in self.url else '?') + querystr)

     def _urlencode(seq, enc):
        values = [(to_bytes(k, enc), to_bytes(v, enc))
                  for k, vs in seq
                  for v in (vs if is_listlike(vs) else [vs])]
        return urlencode(values, doseq=True)

阅读源码可以得知:
FormRequest:只能提交表单数据
FormRequest会将 formdata 传递的字典转化为 urlencode 进行 表单 数据的提交

FormRequest Demo
yield FormRequest(
            method='post',
            url=base_url,
            headers=headers,
            formdata=data,
            callback=self.parse
        )

Json

方法一

from scrapy.http.request.json_request import JsonRequest

首先我们阅读下JsonRequest源码:

class JsonRequest(Request):
    def __init__(self, *args, **kwargs):
        dumps_kwargs = copy.deepcopy(kwargs.pop('dumps_kwargs', {}))
        dumps_kwargs.setdefault('sort_keys', True)
        self._dumps_kwargs = dumps_kwargs

        body_passed = kwargs.get('body', None) is not None
        data = kwargs.pop('data', None)
        data_passed = data is not None

        if body_passed and data_passed:
            warnings.warn('Both body and data passed. data will be ignored')

        elif not body_passed and data_passed:
            kwargs['body'] = self._dumps(data)

            if 'method' not in kwargs:
                kwargs['method'] = 'POST'

        super().__init__(*args, **kwargs)
        self.headers.setdefault('Content-Type', 'application/json')
        self.headers.setdefault('Accept', 'application/json, text/javascript, */*; q=0.01')

    def replace(self, *args, **kwargs):
        body_passed = kwargs.get('body', None) is not None
        data = kwargs.pop('data', None)
        data_passed = data is not None

        if body_passed and data_passed:
            warnings.warn('Both body and data passed. data will be ignored')

        elif not body_passed and data_passed:
            kwargs['body'] = self._dumps(data)

        return super().replace(*args, **kwargs)

    def _dumps(self, data):
        """Convert to JSON """
        return json.dumps(data, **self._dumps_kwargs)


JSONRequest = create_deprecated_class("JSONRequest", JsonRequest)

阅读源码可以得知:
JSONRequest 已经做了 json.dumps 操作

JSONRequest Demo
data = {
    'name1': 'value1',
    'name2': 'value2',
}
yield JsonRequest(url='http://www.example.com/post/action', data=data)

方法二

yield Request(url, method="POST", body=json.dumps(data), headers={'Content-Type': 'application/json'},callback=self.parse_json)

相关文章

网友评论

      本文标题:Scrapy和Requests的post请求详解

      本文链接:https://www.haomeiwen.com/subject/blcjeltx.html