在Scrapy中提供了自动爬取网页的CrawlSpider。
一、创建CrawlSpider 项目
1、(1)运行创建项目命令:
python -m scrapy startproject mycwpit
(2)进入爬虫项目:cd mycwpit;运行创建爬虫命令:
python -m scrapy genspider -t crawl steve sohu.com
这里我们使用了名为crawl 的爬虫模版,创建了爬虫文件steve.py;
(3)查看steve.py 文件:
start_urls:设置了要爬取的起始网址;
rules:设置了自动爬行的规则;
LinkExtractor:链接提取器,一般可以用来提取页面中满足条件的链接,供下一次爬取;
parse_item方法:用于编写爬虫的处理过程。
二、链接提取器
rules = (
Rule(LinkExtractor(allow=('.*?/n.*?shtml'),allow_domains=('sohu.com')), callback='parse_item', follow=True),
)
LinkExtrator中的参数及含义:
allow:提取符合对应正则表达式的链接;
deny:不提取符合对应正则表达式的链接;
restrict_xpaths:使用Xpath表达式与allow共同作用提取出同时符合对应Xpath表达式和正则表达式的链接;
allow_domains:允许提取的域名,比如我们想只提取某个域名下的链接时会用到;
deny_domains:不允许提取的域名。
Rule中的其他参数:follow:默认为True,表示跟进,循环爬取;设置为False第一次循环后断开。
三、爬取搜狐网站中的新闻
1、工作流程:
2、编写items.py 文件
import scrapy
class MycwpijItem(scrapy.Item):
#新闻标题
name=scrapy.Field()
#新闻链接
title=scrapy.Field()
3、编写pipelines.py 文件
对爬取到的新闻标题和新闻对应链接进行输出:
class MycwpijPipeline(object):
def process_item(self, item, spider):
print(item["name"])
print(item["title"])
print("-----------------------------")
return item
修改settings.py 文件:
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'mycwpij.pipelines.MycwpijPipeline': 300,
}
4、编写爬虫文件steve.py:
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from mycwpij.items import MycwpijItem
class WeitaoSpider(CrawlSpider):
name = 'steve'
allowed_domains = ['sohu.com']
start_urls = ['http://news.sohu.com/']
rules = (
Rule(LinkExtractor(allow=('.*?/n.*?shtml'),allow_domains=('sohu.com')), callback='parse_item', follow=True),
)
def parse_item(self, response):
i = MycwpijItem()
i["name"]=response.xpath("/html/head/title/text()").extract()
i["title"]=response.xpath("//link[@rel='canonical']/@href").extract()
return i
5、在项目文件路径下打开终端,运行命令:
python -m scrapy crawl steve --nolog
会进行链接的跟进,会一直根据网站中的链接爬取下去,终止爬行:Ctrl+C。
6、爬行结果:
四、另一种利用循环爬取:运用了Scrapy的basic模版
参考示例代码:
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from zhaopin.items import ZhaopinItem
class SteveSpider(scrapy.Spider):
name = 'steve'
#allowed_domains = ['zhaopin.com']
start_urls = ['https://sou.zhaopin.com/?jl=801']
def parse(self, response):
item = ZhaopinItem()
item["jobName"] = response.xpath("//div[@class='jobName']/a/span[@class='job_title']/@title").extract()
item['companyName'] = response.xpath("//div[@class='companyName']/a[@class='company-title']/@title").extract()
item['salary'] = response.xpath("//p[@class='job_saray']/text()").extract()
item['job_demand'] = response.xpath("//ul[@class='job_demand']/li[@class='demand_item']/text()").extract()
item['companyType'] = response.xpath("//div[@class='companyDesc']/span[@class='info_item']/text()").extract()
#返回item
yield item
for i in range(1, 3):
url="https://sou.zhaopin.com/?p="+str(i)+"&jl=801"
#通过yield返回Request,并且指定要爬取的网址和回调函数
#实现自动爬取
yield Request(url, callback=self.parse)