在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)