需求 想要爬去糗事百科全站的数据python
方法:框架
(1)基于Scrapy框架中的Spider的递归爬去实现dom
(2) 基于Scrapy框架的CrawlSpider的自动爬取来进行实现scrapy
那么CrawlSpider又是什么呢?如何实现它的自动爬取?ide
crawlspider是spider的一个子类,除了继承到Spider的功能外,还派生了其本身的更强大的功能和特性。其中最显著的功能就是'”LinkExtractors连接提取器'。Spider是全部怕爬虫类的基类网站
步骤:url
(1)建立scrapy工程:scrapy startproject projectNamespa
(2) 建立爬虫文件:scrapy genspider -t crawl spidername www.xxx.comcode
(3)生成的爬虫文件和以前的spider基类的爬虫文件有所不一样继承
需求 爬取到抽屉网站中分页中的url
import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule #爬取抽屉网站的分页的URL #注意 这里继承的类是CrawlSpider 而不是Spider class ChoutiSpider(CrawlSpider): name = 'chouti' # allowed_domains = ['www.xxx.com'] start_urls = ['https://dig.chouti.com/r/scoff/hot/1'] #allow表示连接提取器提取连接的规则 rules = ( #Rule 规则提取器:将连接提取器提取到的连接所对应的页面进行指定形式的解析 #follow 让链接提取器继续做用到连接提取器提取到的连接所对应的页面中 Rule(LinkExtractor(allow=r'/r/scoff/hot/\d+'), callback='parse_item', follow=True), ) def parse_item(self, response): print(response) item = {} item['domain_id'] = response.xpath('//input[@id="sid"]/@value').get() item['name'] = response.xpath('//div[@id="name"]').get() item['description'] = response.xpath('//div[@id="description"]').get() return item
需求 爬取糗事百科网站的分页的URL
#爬取糗事百科网站的分页的URL class ChoutiSpider(CrawlSpider): name = 'qiubai' # allowed_domains = ['www.xxx.com'] start_urls = ['https://www.qiushibaike.com/pic/'] #allow表示连接提取器提取连接的规则 link = LinkExtractor(allow=r'/pic/page/\d+\?s=\d+') link1 = LinkExtractor(allow=r'/pic/$') #注意这里能够有多个规则 rules = ( #Rule 规则提取器:将连接提取器提取到的连接所对应的页面进行指定形式的解析 #follow 让链接提取器继续做用到连接提取器提取到的连接所对应的页面中 Rule(link, callback='parse_item', follow=True), Rule(link1,callback='parse_item',follow=True) ) def parse_item(self, response): print(response)