#CrawlSpider需要使用:规则提取器和解析器#1.allow设置规则的方法:要能够限制在目标url上面,不要跟其他的url产生相同的正则即可#2.什么情况下使用follow:如果在爬取页面的时候,需要将满足条件的url再进行跟进,那么就设置为True,否则是False#3.什么情况下使用callack:如果这个url对应的页面只是为了获取更多的url,并不需要里面的数据,那么可以不指定callback.如果想要获取url对应页面里的数据,那么就需要指定callback#spider文件importscrapyfromscrapy.linkextractorsimportLinkExtractorfromscrapy.spidersimportCrawlSpider,Rulefromwxapp.itemsimportWxappItemclassWxappspiderSpider(CrawlSpider):name='wxappSpider'allowed_domains=['wxapp-union.com']start_urls=['http://www.wxapp-union.com/portal.php?mod=list&catid=2&page=1']rules=(Rule(LinkExtractor(allow=r'http://www.wxapp-union.com/portal.php?mod=list&catid=2&page=d'),follow=True),Rule(LinkExtractor(allow=r'.+article-.+.html'),callback='parse_detail',follow=False),)defparse_detail(self,response):#解析详情页#print(response)#200http://www.wxapp-union.com/article-5137-1.html详情页title=response.xpath('//h1[@]/text()').extract_first()author=response.xpath('//p[@]/a/text()').extract_first()content=response.xpath('//td[@id="article_content"]//text()').extract()content="".join(content).strip()print(content)print("=="20)item=WxappItem(title=title,author=author,content=content)yielditem#管道文件保存在json文件里fromscrapy.exportersimportJsonItemExporterfromscrapy.exportersimportJsonLinesItemExporter#要存的数据量大的时候用这个classWxappPipeline(object):def__init__(self):self.fp=open("weixinjiaocheng.json","wb")self.exporter=JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')defprocess_item(self,item,spider):self.exporter.export_item(item)returnitemdefclose_spider(self,spider):self.fp.close()

TAG标签: 微信小程序小程序微信小程序社区

http://www.xiaochengxub.com/read-107608.html