Python 使用 Scrapy 发送 post 请求的坑

 

From:https://www.jb51.net/article/146769.htm

 

使用 requests 发送 post 请求

 

先来看看使用requests来发送post请求是多少好用,发送请求
Requests 简便的 API 意味着所有 HTTP 请求类型都是显而易见的。
例如,你可以这样发送一个 HTTP POST 请求:

>>>r = requests.post('http://httpbin.org/post', data = {'key':'value'})

使用data可以传递字典作为参数,同时也可以传递元祖

>>>payload = (('key1', 'value1'), ('key1', 'value2'))
>>>r = requests.post('http://httpbin.org/post', data=payload)
>>>print(r.text)
{..."form": {"key1": ["value1","value2"]},...
}

传递 json 是这样

>>>import json>>>url = 'https://api.github.com/some/endpoint'
>>>payload = {'some': 'data'}>>>r = requests.post(url, data=json.dumps(payload))

2.4.2 版的新加功能:

>>>url = 'https://api.github.com/some/endpoint'
>>>payload = {'some': 'data'}>>>r = requests.post(url, json=payload)

也就是说,你不需要对参数做什么变化,只需要关注使用data=还是json=,其余的requests都已经帮你做好了。

 

 

使用scrapy发送post请求

 

通过源码可知scrapy默认发送的get请求,当我们需要发送携带参数的请求或登录时,是需要post、请求的,以下面为例

from scrapy.spider import CrawlSpider
from scrapy.selector import Selector
import scrapy
import json
class LaGou(CrawlSpider):name = 'myspider'def start_requests(self):yield scrapy.FormRequest(url='https://www.******.com/jobs/positionAjax.json?city=%E5%B9%BF%E5%B7%9E&needAddtionalResult=false',formdata={'first': 'true',#这里不能给bool类型的True,requests模块中可以'pn': '1',#这里不能给int类型的1,requests模块中可以'kd': 'python'},  # 这里的formdata相当于requ模块中的data,key和value只能是键值对形式callback=self.parse)def parse(self, response):datas=json.loads(response.body.decode())['content']['positionResult']['result']for data in datas:print(data['companyFullName'] + str(data['positionId']))

官方推荐的 Using FormRequest to send data via HTTP POST

return [FormRequest(url="http://www.example.com/post/action",formdata={'name': 'John Doe', 'age': '27'},callback=self.after_post)]

这里使用的是FormRequest,并使用formdata传递参数,看到这里也是一个字典。

但是,超级坑的一点来了,今天折腾了一下午,使用这种方法发送请求,怎么发都会出问题,返回的数据一直都不是我想要的

return scrapy.FormRequest(url, formdata=(payload))

在网上找了很久,最终找到一种方法,使用scrapy.Request发送请求,就可以正常的获取数据。

return scrapy.Request(url, body=json.dumps(payload), method='POST', headers={'Content-Type': 'application/json'},)

参考:Send Post Request in Scrapy

my_data = {'field1': 'value1', 'field2': 'value2'}
request = scrapy.Request( url, method='POST', body=json.dumps(my_data), headers={'Content-Type':'application/json'} )

 

 

FormRequest 与 Request 区别

 

在文档中,几乎看不到差别,

The FormRequest class adds a new argument to the constructor. The remaining arguments are the same as for the Request class and are not documented here.
Parameters: formdata (dict or iterable of tuples) – is a dictionary (or iterable of (key, value) tuples) containing HTML Form data which will be url-encoded and assigned to the body of the request.

说FormRequest新增加了一个参数formdata,接受包含表单数据的字典或者可迭代的元组,并将其转化为请求的body。并且FormRequest是继承Request的

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 formdataquerystr = _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 seqfor v in (vs if is_listlike(vs) else [vs])]return urlencode(values, doseq=1)

最终我们传递的{‘key': ‘value', ‘k': ‘v'}会被转化为'key=value&k=v' 并且默认的method是POST,再来看看Request

class Request(object_ref):def __init__(self, url, callback=None, method='GET', headers=None, body=None,cookies=None, meta=None, encoding='utf-8', priority=0,dont_filter=False, errback=None, flags=None):self._encoding = encoding # this one has to be set firstself.method = str(method).upper()

默认的方法是GET,其实并不影响。仍然可以发送post请求。这让我想起来requests中的request用法,这是定义请求的基础方法。

def request(method, url, **kwargs):"""Constructs and sends a :class:`Request <Request>`.:param method: method for the new :class:`Request` object.:param url: URL for the new :class:`Request` object.:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.:param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.:param json: (optional) json data to send in the body of the :class:`Request`.:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a stringdefining the content type of the given file and ``custom_headers`` a dict-like object containing additional headersto add for the file.:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.:param timeout: (optional) How many seconds to wait for the server to send databefore giving up, as a float, or a :ref:`(connect timeout, readtimeout) <timeouts>` tuple.:type timeout: float or tuple:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.:type allow_redirects: bool:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.:param verify: (optional) Either a boolean, in which case it controls whether we verifythe server's TLS certificate, or a string, in which case it must be a pathto a CA bundle to use. Defaults to ``True``.:param stream: (optional) if ``False``, the response content will be immediately downloaded.:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.:return: :class:`Response <Response>` object:rtype: requests.ResponseUsage::>>> import requests>>> req = requests.request('GET', 'http://httpbin.org/get')<Response [200]>"""# By using the 'with' statement we are sure the session is closed, thus we# avoid leaving sockets open which can trigger a ResourceWarning in some# cases, and look like a memory leak in others.with sessions.Session() as session:return session.request(method=method, url=url, **kwargs)

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/496105.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Effective Java~46. 优先选择Stream 中无副作用的函数

纯函数&#xff08;pure function&#xff09;的结果仅取决于其输入&#xff1a;它不依赖于任何可变状态&#xff0c;也不更新任何状态。 坏味道 // Uses the streams API but not the paradigm--Dont do this! Map<String, Long> freq new HashMap<>(); try (S…

android applybatch,android – 使用applyBatch插入成千上万的联系人条目很慢

我正在开发一个应用程序&#xff0c;我需要插入大量的联系人条目。在当前时间约600个联系人&#xff0c;共有6000个电话号码。最大的联系人有1800个电话号码。截至今天的状态是&#xff0c;我创建了一个自定义帐户来保存联系人&#xff0c;因此用户可以选择在联系人视图中查看联…

[译]How to make searching faster

Here are some things to try to speed up the seaching speed of your Lucene application. Please see ImproveIndexingSpeed for how to speed up indexing. 以下是一些尝试提高lucene程序检索速度的方法. 如果需要提高索引速度,请看提高索引速度. Be sure you really need …

8个最高效的Python爬虫框架,你用过几个?

From&#xff1a;https://segmentfault.com/a/1190000015131017 1.Scrapy Scrapy是一个为了爬取网站数据&#xff0c;提取结构性数据而编写的应用框架。 可以应用在包括数据挖掘&#xff0c;信息处理或存储历史数据等一系列的程序中。。用这个框架可以轻松爬下来如亚马逊商品信…

android oreo 源码,android – Oreo:如何在源代码中找到所有受限制的系统调用?

哪些Syscalls在Android 8.0 Oreo中受限制&#xff1f;编辑&#xff1a;Syscall过滤背景过滤本身是Linux内核提供的标准功能,称为seccomp.所有AOSP都使用此功能来过滤上面链接的应用黑名单中列出的系统调用.脚本处理将黑名单列入特定于平台的自动生成过滤器,然后将其提供给secco…

Effective Java~57. 将局部变量的作用域最小化

优先选择 for 循环而不是 while 循环 例如&#xff0c;下面是遍历集合的首选方式 // Preferred idiom for iterating over a collection or array for (Element e : c) { ... // Do Something with e } 如果需要在循环中调用 remove 方法&#xff0c;首选传统的 for 循环代…

300+Jquery, CSS, MooTools 和 JS的导航菜单资源

如果你是网站前端开发人员&#xff0c;那么对你来说&#xff0c;也许做一个漂亮导航菜单会很得心应手。本文要为大家总结各种导航菜单的资源&#xff0c;以便让大家的网站前端开发的工作更方便更快速&#xff0c;只要选择现成的例子就可以应用于自己的网站了。本文收集的这些资…

轻量级分布式任务调度平台 XXL-JOB

From&#xff1a;https://www.cnblogs.com/xuxueli/p/5021979.html github 地址 及 中文文档地址&#xff1a;https://github.com/xuxueli/xxl-job 《分布式任务调度平台XXL-JOB》 一、简介 1.1 概述 XXL-JOB是一个轻量级分布式任务调度平台&#xff0c;其核心设计目标是开发…

畅玩4c刷android 9.0,华为畅玩4C电信版 CyanogenMod 13.0_Android_6.0.1 【HRT_chiwahfj】

本帖最后由 chiwah渔夫 于 2016-9-9 22:31 编辑【基本信息】ROM名称&#xff1a;华为畅玩4C电信版 CyanogenMod 13.0_Android_6.0.1ROM大小&#xff1a;617M适配版本&#xff1a;CyanogenMod 13.0_android_6.0.1测试机型&#xff1a;华为畅玩4C电信版作者简介&#xff1a;HRT团…

Effective Java~58. for-each 循环优先于传统的for 循环

传统的 for循环来遍历一个集合: // Not the best way to iterate over a collection! for (Iterator<Element> i c.iterator(); i.hasNext(); ) { Element e i.next();... // Do something with e } 迭代数组的传统 for 循环的实例 // Not the best way to iterate …

近期课余目标

http://acm.pku.edu.cn/JudgeOnline/ 按这个顺序做&#xff0c; 这些都是入门的水题 一.基本算法: (1)枚举. (poj1753,poj2965) (2)贪心(poj1328,poj2109,poj2586) (3)递归和分治法. (4)递推. (5)构造法.(poj3295) (6)模拟法.(poj1068,poj2632,poj1573,poj2993,poj2996) 二.图算…

html语言鼠标悬停特效,CSS3鼠标悬停文字幻影动画特效

这是一款CSS3鼠标悬停文字幻影动画特效。该特效利用before和after伪元素来制作当鼠标悬停在超链接文本上的时候的幻影效果。使用方法在页面中引入bootstrap.css、jquery和photoviewer.js文件。HTML结构在页面中添加一个元素&#xff0c;并设置它的data-hover属性和它的显示文字…

Python 爬虫 实例项目 大全

Github Python 爬虫&#xff1a;https://github.com/search?qpython爬虫 32个Python爬虫项目让你一次吃到撑&#xff1a;https://www.77169.com/html/170460.html 今天为大家整理了32个Python爬虫项目。 整理的原因是&#xff0c;爬虫入门简单快速&#xff0c;也非常适合新入…

Effective Java~23. 类层次优于标签类

标签类&#xff0c;包含一个标签属性&#xff08;tag field&#xff09;&#xff0c;表示实例的风格 // Tagged class - vastly inferior to a class hierarchy! class Figure {enum Shape { RECTANGLE, CIRCLE };// Tag field - the shape of this figurefinal Shape shape;/…

领导之所以是领导

最近系统很不安生&#xff0c;故障频出&#xff0c;12月30日下午15&#xff1a;00系统所有工单都无法在网元开通&#xff0c;用户缴费不能开机&#xff0c;只好手工执行&#xff0c;直到23&#xff1a;30才恢复。1月1日某个业务平台执行工单异常缓慢&#xff0c;导致系统1万多工…

可以叫板Google的一个搜索引擎 —— DuckDuckGo

From&#xff1a;https://blog.csdn.net/inter_peng/article/details/53223455 作为习惯了使用Google进行资料查询的我来说&#xff0c;如果没有Google&#xff0c;真的感觉很难受。纵使找了一些可以翻墙的软件&#xff0c;但无奈还是经常不稳定&#xff0c;总是时断时续的。Bi…

小米鸿蒙1001小米鸿蒙,小米高管早就放下狠话!愿意使用鸿蒙2.0系统:那其他厂商呢?...

【9月14日讯】相信大家都知道&#xff0c;自从华为鸿蒙OS系统2.0版本正式发布以后&#xff0c;由于华为消费者业务CEO余承东正式确认&#xff1a;“华为手机在12月开始适配鸿蒙OS系统&#xff0c;明年所有华为手机全面启用鸿蒙OS系统。” 这也意味着国产智能手机厂商也将彻底的…

Effective Java~26. 不要使用 raw type

在编译完成之后尽快发现错误是值得的&#xff0c;理想情况是在编译时 在泛型被添加到 Java 之前&#xff0c;这是一个典型的集合声明 // Raw collection type - dont do this! // My stamp collection. Contains only Stamp instances. private final Collection stamps ...…

WCF中的管道——管道类型

管道是所有消息进出WCF应用程序的渠道。它的职责是以统一的方式编制和提供消息。管道中定义了传输、协议和消息拦截。管道以层级结构的形式汇总&#xff0c;就创建了一个管道栈。管道栈以分层的方式进行通信并处理消息。例如&#xff0c;一个管道栈可以使用一个TCP协议管道和一…

android德州扑克计算器,学界 | 一台笔记本打败超算:CMU冷扑大师团队提出全新德扑AI Modicum...

原标题&#xff1a;学界 | 一台笔记本打败超算&#xff1a;CMU冷扑大师团队提出全新德扑AI Modicum选自arXiv参与&#xff1a;路、晓坤CMU 冷扑大师团队在读博士 Noam Brown、Tuomas Sandholm 教授和研究助理 Brandon Amos 近日提交了一个新研究&#xff1a;德州扑克人工智能 M…