门户网站跳出率,在华图做网站编辑,wordpress同步到,网址类网站怎么做CrawpSpider和Spider的区别
CrawlSpider使用基于规则的方式来定义如何跟踪链接和提取数据。它支持定义规则来自动跟踪链接#xff0c;并可以根据链接的特征来确定如何爬取和提取数据。CrawlSpider可以对多个页面进行同样的操作#xff0c;所以可以爬取全站的数据。CrawlSpid…CrawpSpider和Spider的区别
CrawlSpider使用基于规则的方式来定义如何跟踪链接和提取数据。它支持定义规则来自动跟踪链接并可以根据链接的特征来确定如何爬取和提取数据。CrawlSpider可以对多个页面进行同样的操作所以可以爬取全站的数据。CrawlSpider可以使用LinkExtractor用正则表达式自动提取链接而不需要手动编写链接提取代码。 Spider和CrawlSpider都是Scrapy的Spider类的子类。 注意CrawlSpider是不支持请求传参的(多个parse函数的参数之间的来回传递)
CrawlSpider使用步骤
创建一个工程 XXXPro scrapy startproject XXXProcd XXXPro创建爬虫文件CrawlSpiderscrapy genspider -t crawl xxx www.xxxx.com 链接提取器LinkExtractor根据指定的规则allow正则表达式进行指定链接的提取规则解析器Rule将链接提取器提取到的链接进行指定规则callback的解析
爬取全页的链接 我们可以根据每页的链接形式使用正则表达式来进行提取。 通过使用下面的链接提取器可以得到所有页面的链接而且虽然提取到的链接是不全的CrawlSpider还会自动补全。 link LinkExtractor(allowr/content/node_21745_) # 这个链接提取器是用于在页面源码中根据制定规则进行正则匹配的爬取每个新闻详情页的url link_detail LinkExtractor(allowr/content/20)补充规则解析器 rules (Rule(link, callbackparse_item, followFalse), # #followTrue可以将链接提取器 继续作用到 连接提取器提取到的链接 所对应的页面中Rule(link_detail, callbackparse_detail, followFalse))
parse解析函数
# 解析新闻标题def parse_item(self, response):# 注意xpath表达式中不可以出现tbody标签a_list response.xpath(/html/body/section[2]/div[3]/div[2]/div[1]/div[4]/ul/a)# print(li_list)for a in a_list:title a.xpath(./li/p/text()).extract_first()item SunproItem()item[title] title# print( title:, title)yield itemprint(len(a_list))# 解析新闻内容def parse_detail(self, response):# print(parse_detail正在执行)content response.xpath(//*[idnews_con]//text()).extract()content .join(content)item DetailItem()item[content] content# print(news content:, content)yield itempipelines管道类
class SunproPipeline:def process_item(self, item, spider):if item.__class__.__name__ SunproItem:print(item[title])else:print(item[content])return item
注意要在setings.py中开启管道类