API 参考
1. self.crawl
self.cracl(url, **kwargs)
self.cracl
是告诉pyspider应该爬取哪个url的主要接口程序。
参数
url
需要爬取的url或者url列表
callback
解析返回响应的方法
def on_start(self):
self.crawl('http://scrapy.org/', callback=self.index_page)
以下的参数可选
age
任务的有效期。在此期间,该页面将被视为未修改。默认值:-1(从不重新抓取)
@config(age=10 * 24 * 60 * 60)
def index_page(self, response):
...
每个被index_page
解析的页面将被视为十天内不会发生改变,如果您在上次爬取后的十天内提交任务,它将被丢弃
priority
待调度任务优先级越高,优先级越大。默认值:0
def index_page(self):
self.crawl('http://www.example.org/page2.html', callback=self.index_page)
self.crawl('http://www.example.org/233.html', callback=self.detail_page,
priority=1)
页面233.html
将会比page2.html
优先爬取,使用此参数执行广度优先算法从而减少队列中任务的数量,控制内存资源。
exetime
任务的执行时间(时间戳)。默认:0 (立即运行)
import time
def on_start(self):
self.crawl('http://www.example.org/', callback=self.callback,
exetime=time.time()+30*60)
该页面将在30分钟后运行
retries
失败的重试次数。默认:3
itag
来自前沿页面的标记,用于显示任务的潜在修改。它将与其最后一个值进行比较,更改后重新爬取。默认:None
def index_page(self, response):
for item in response.doc('.item').items():
self.crawl(item.find('a').attr.url, callback=self.detail_page,
itag=item.find('.update-time').text())
在上面的例子中,.update-time
作为itag。如果没有更改,请求将被丢弃。
或者如果希望重新启动所有的任务,你可以通过Handler.crawl_config
来设置itag
,指定脚本的版本。
class Handler(BaseHandler):
crawl_config = {
'itag': 'v223'
}
修改脚本后更改itag的值,然后再次单击run按钮。如果之前没有设置,也没有关系。
auto_recrawl
当启用时,任务会在每个生命周期重新爬取。默认:False
def on_start(self):
self.crawl('http://www.example.org/', callback=self.callback,
age=5*60*60, auto_recrawl=True)
每5个小时页面会被重新爬取。
method
使用的http请求方法。默认:GET
params
要附加到URL的URL参数字典。
def on_start(self):
self.crawl('http://httpbin.org/get', callback=self.callback,
params={'a': 123, 'b': 'c'})
self.crawl('http://httpbin.org/get?a=123&b=c', callback=self.callback)
这两个请求相同。
data
附加到请求的请求体。如果提供字典,则将进行表单编码。
def on_start(self):
self.crawl('http://httpbin.org/post', callback=self.callback,
method='POST', data={'a': 123, 'b': 'c'})
user_agent
请求的用户代理
headers
要发送的请求头字典。
cookies
要附加到请求的cookie字典
timeout
获取页面的最长时间(秒)。默认:120
allow_redirects
遵循30x
重定向,默认:True
save
一个传递给回调方法的对象,可以通过response.save访问
def on_start(self):
self.crawl('http://www.example.org/', callback=self.callback,
save={'a': 123})
def callback(self, response):
return response.save['a']
123
将在callback里返回。
last_modified
如果页面内容未更改,请使用HTTP Last-Modified标头机制来传递进程。默认值:True
validate_cert = False
不检验证书
2. Response
响应对象的属性。
Response.url
最终的URL
Response.text
unicode编码的响应文本。
如果Response.encoding
为None,charset
模块可用,内容编码将会被猜测。
Response.content
二进制格式的响应内容。
Response.doc
响应内容的PyQuery对象。
参考PyQuery的文档:https://pythonhosted.org/pyquery/
Response.etree
响应内容的lxml对象。
Response.json
响应的json编码内容(如果有的话)。
以上是pyspider 的部分 API参数,详细参考http://docs.pyspider.org/en/latest/apis/Response/