【python爬虫学习笔记】09 Scrapy爬虫的数据类型及yield关键字
Yield关键字
yield<—>生成器
生成器是一个不断产生值的函数
包含yield语句的函数是一个生成器
生成器每次产生一个值(yield语句),函数被冻结,被唤醒后再产生一个值
具体使用:
class DemoSpider(scrapy.Spider):
name = 'demo'
def start_requests(self):
urls=[
'http://python123.io/ws/demo.html'
]
for url in urls:
yield scrapy.Request(url=url,callback=self.parse)
def parse(self, response):
fname = response.url.split('/')[-1]
with open(fname,'wb') as f:
f.write(response.body)
self.log('Saved file %s.' % name)
pass
Scrapy爬虫的数据类型
Request类
class scrapy.http.Request()
Request对象表示一个HTTP请求
由Spider生成,最终由Downloader执行
Response类
class scrapy.http.Response()
Response对象表示一个HTTP响应
由Downloader生成,由Spider处理
Item类
class scrapy.item.Item()
Item对象表示一个从HTML页面中提取的信息内容
由Spider生成,由Item Pipeline处理
Item类似字典类型,可以按照字典类型操作
Scrapy爬虫提取信息的方法
Scrapy爬虫支持多种HTML信息提取方法
-
BeautifulSoup
-
Ixml
-
re
-
XPath Selector
-
CSS Selector
a:标签名称
href:标签属性