scrapy请求与响应
Request对象:
一个Request对象代表着一个HTTP请求,通常在Spider类中产生,然后传递给下载器,最后返回一个响应
类原型:class scrapy.http.Request(url[, callback, method='GET', headers, body, cookies, meta, encoding='utf-8', priority=0, dont_filter=False, errback])
构造参数说明:
url(string) - 此请求的网址
callback(callable) - 将使用此请求的响应(一旦下载)作为其第一个参数调用的函数。如果请求没有指定回调,parse()将使用spider的 方法。请注意,如果在处理期间引发异常,则会调用errback。
method(string) - 此请求的HTTP方法。默认为’GET’。
meta(dict) - 属性的初始值Request.meta。如果给定,在此参数中传递的dict将被浅复制。
body(str或unicode) - 请求体。如果unicode传递了a,那么它被编码为 str使用传递的编码(默认为utf-8)。- 如果 body没有给出,则存储一个空字符串。不管这个参数的类型,存储的最终值将是一个str(不会是unicode或None)。
headers(dict) - 这个请求的头。dict值可以是字符串(对于单值标头)或列表(对于多值标头)。如果 None作为值传递,则不会发送HTTP头。
cookie(dict或list) - 请求cookie。这些可以以两种形式发送。
encoding(string) - 此请求的编码(默认为’utf-8’)。此编码将用于对URL进行百分比编码,并将正文转换为str(如果给定unicode)。
priority(int) - 此请求的优先级(默认为0)。调度器使用优先级来定义用于处理请求的顺序。具有较高优先级值的请求将较早执行。允许负值以指示相对低优先级。
dont_filter(boolean) - 表示此请求不应由调度程序过滤。当您想要多次执行相同的请求时忽略重复过滤器时使用。小心使用它,或者你会进入爬行循环。默认为False。
errback(callable) - 如果在处理请求时引发任何异常,将调用的函数。这包括失败的404 HTTP错误等页面。
cookies参数设置的两种方法
使用字典request_with_cookies = Request(url="http://www.example.com", cookies={'currency': 'USD', 'country': 'UY'})使用字典列表发送
request_with_cookies = Request(url="http://www.example.com", cookies=[{'name': 'currency', 'value': 'USD', 'domain': 'example.com', 'path': '/currency'}])当某些网站返回Cookie(在响应中)时,这些Cookie会存储在该域的Cookie中,并在将来的请求中再次发送。这是任何常规网络浏览器的典型行为。但是,如果由于某种原因,想要避免与现有Cookie合并,可以设置Requ.meta中dont_merge_cookies字段的值。示例如下
request_with_cookies = Request(url="http://www.example.com", cookies={'currency': 'USD', 'country': 'UY'}, meta={'dont_merge_cookies': True})
errback的使用方法示例:
import scrapyfrom scrapy.spidermiddlewares.httperror import HttpErrorfrom twisted.internet.error import DNSLookupErrorfrom twisted.internet.error import TimeoutError, TCPTimedOutErrorclass ErrbackSpider(scrapy.Spider): name = "errback_example" start_urls = [ "http://www.httpbin.org/", # HTTP 200 expected "http://www.httpbin.org/status/404", # Not found error "http://www.httpbin.org/status/500", # server issue "http://www.httpbin.org:12345/", # non-responding host, timeout expected "http://www.httphttpbinbin.org/", # DNS error expected ] def start_requests(self): for u in self.start_urls: yield scrapy.Request(u, callback=self.parse_httpbin, errback=self.errback_httpbin, dont_filter=True) def parse_httpbin(self, response): self.logger.info('Got successful response from {}'.format(response.url)) # do something useful here... def errback_httpbin(self, failure): # log all failures self.logger.error(repr(failure)) # in case you want to do something special for some errors, # you may need the failure's type: if failure.check(HttpError): # these exceptions come from HttpError spider middleware # you can get the non-200 response response = failure.value.response self.logger.error('HttpError on %s', response.url) elif failure.check(DNSLookupError): # this is the original request request = failure.request self.logger.error('DNSLookupError on %s', request.url) elif failure.check(TimeoutError, TCPTimedOutError): request = failure.request self.logger.error('TimeoutError on %s', request.url)
下面写的是Request的子类 FormRquest类,专门用来处理html表单,尤其对隐藏表单的处理非常方便,适合用来完成登录操作
类原型:class scrapy.http.FormRequest(url[, formdata, ...])
其中构造参数formdata可以是字典,也可以是可迭代的(key,value)元祖,代表着需要提交的表单数据。
示例如下:
return [FormRequest(url="http://www.example.com/post/action", formdata={'name': 'John Doe', 'age': '27'}, callback=self.after_post)]
通常网站通过<input type="hidden">实现对某些表单字段的预填充,就像知乎的隐藏表单的_xfv数值,Scray在FromRequest类提供了一个类方法from_reponse来解决隐藏表单这个问题。方法原型如下:
classmethod from_response(response[, formname=None, formid=None, formnumber=0, formdata=None, formxpath=None, formcss=None, clickdata=None, dont_click=False, ...])
参数说明:
response(Responseobject) - 包含将用于预填充表单字段的HTML表单的响应
formname(string) - 如果给定,将使用name属性设置为此值的形式。
formid(string) - 如果给定,将使用id属性设置为此值的形式。
formxpath(string) - 如果给定,将使用匹配xpath的第一个表单。
formcss(string) - 如果给定,将使用匹配css选择器的第一个形式。
formnumber(integer) - 当响应包含多个表单时要使用的表单的数量。第一个(也是默认)是0。
formdata(dict) - 要在表单数据中覆盖的字段。如果响应元素中已存在字段,则其值将被在此参数中传递的值覆盖。
clickdata(dict) - 查找控件被点击的属性。如果没有提供,表单数据将被提交,模拟第一个可点击元素的点击。除了html属性,控件可以通过其相对于表单中其他提交表输入的基于零的索引,通过nr属性来标识。
dont_click(boolean) - 如果为True,表单数据将在不点击任何元素的情况下提交。
下面是一个实现登录功能的示例代码:
import scrapyclass LoginSpider(scrapy.Spider): name = 'example.com' start_urls = ['http://www.example.com/users/login.php'] def parse(self, response): return scrapy.FormRequest.from_response( response, formdata={'username': 'john', 'password': 'secret'}, callback=self.after_login ) def after_login(self, response): # check login succeed before going on if "authentication failed" in response.body: self.logger.error("Login failed") return
- 版权申明:此文如未标注转载均为本站原创,自由转载请表明出处《龙行博客》。
- 本文网址:https://www.liaotaoo.cn/303.html
- 上篇文章:推荐一个好用的ip代理池
- 下篇文章:scrapy内置图片和文件下载