scrapy把爬取数据和处理数据分别放在以下两个位置(itcast为我们创建的爬虫名)
数据爬取的代码如下(其中parse方法中的response是请求start_urls的返回):
import scrapy
class ItcastSpider(scrapy.Spider):
name = 'itcast' #爬虫名字
allowed_domains = ['itcast.cn'] #爬取范围
start_urls = ['http://www.itcast.cn/channel/teacher.shtml?jingjiaczpz-PC-1'] #爬取url
# 对url响应的处理
def parse(self, response):
#print(response.xpath("//div[@class='tea_con']/div/ul/li/h3/text()"))
#extract返回的是一个类似于list
#res = response.xpath("//div[@class='tea_con']/div/ul/li//h3/text()").extract()
li_list=response.xpath("//div[@class='tea_con']/div/ul/li")
for li in li_list:
item={}
#extract_first返回的是第一个字符串,如果为空,就返回None
item["name"]=li.xpath(".//h3/text()").extract_first()
item["level"]=li.xpath(".//h4/text()").extract_first()
item["desc"]=li.xpath(".//p/text()").extract_first()
yield item#使用yield方便数据处理,且只能yield dic、None、Request、BaseItem
接下来就是数据处理:
首先我们要在配置文件中打开
ITEM_PIPELINES = {
'mySpider.pipelines.MyspiderPipeline': 300,
'mySpider.pipelines.MyspiderPipeline1': 301,
}
其中键为管道的地址,值为管道离引擎的距离,距离越小,越优先执行
接下来在管道中进行数据处理
class MyspiderPipeline:
def process_item(self, item, spider):
if spider.name=="itcast":
print(item)
return item
class MyspiderPipeline1:
def process_item(self, item, spider):
if spider.name == "itcast":
print(item)
return item
process_item()方法中的item即为yield的内容,spider为这个item是哪个爬虫的,所以我们可以对不同的爬虫采取不同的处理。
因为第一个管道的距离小于第二个 所以先执行第一个,在字典中添加一个a属性,然后第二个管道进行输出(注意:当后一个管道需要使用前一个管道的结果时,前一个管道需要return)