赞
踩
作者:Irain
QQ:2573396010
微信:18802080892
视频资源链接:https://www.bilibili.com/video/BV1P4411f7rP?p=83.
scrapy startproject wxapp # 创建项目
cd wxapp # 进入项目文件夹
scrapy genspider -t crawl wxapp_spider "wxapp-union.com" # 创建爬虫
# CrawlSpider爬虫 与 普通爬虫 创建方式不一样
allow : 设置规则,获取目标url,排除其他url。
follow : 在当前url下,是否继续获取满足allow规则的url。
callback : 对当前的url进行操作(提取url或元素)。
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from wxapp.items import WxappItem class WxappSpiderSpider(CrawlSpider): name = 'wxapp_spider' # 爬虫名字 allowed_domains = ['wxapp-union.com'] # 网站域名 start_urls = ['http://www.wxapp-union.com/portal.php?mod=list&catid=2&page=1'] # 起始网页 rules = ( # allow:需要爬取的网页; follow:是否继续爬取下一页 Rule(LinkExtractor(allow=r'.+mod=list&catid=2&page=\d'), follow=True), # callback:提取详情网页内容 # follow=False: 防止重复爬取。因为:在详情网页中出现其他符合爬取规格的网页。 Rule(LinkExtractor(allow=r'.+article-.+\.html'), callback="parse_detail", follow=False), ) def parse_detail(self, response): # 爬取详情网页 title = response.xpath("//*[@id='ct']/div[1]/div/div[1]/div/div[2]/div[1]/h1/text()").get() # 提起文章标题 author = response.xpath("//p[@class='authors']//a/text()").get() # 提起作者 time = response.xpath("//*[@id='ct']/div[1]/div/div[1]/div/div[2]/div[3]/div[1]/p/span/text()").get() # 提起发表时间 content = response.xpath("//td//text()").getall() # 提起文章内容 content = "".join(content).strip() # list类型转换为字符型 item = WxappItem(title=title, author=author, time=time, content=content) # 传参 yield item # item传给管道pipelines print("=" * 40)
from scrapy.exporters import JsonLinesItemExporter # 一条一条数据存入磁盘,占用内存小
class WxappPipeline(object):
def __init__(self):
self.fp = open("wxjc.json","wb") # 二进制方式写入,不需要编码格式
# ensure_ascii:中文字符
self.exporters = JsonLinesItemExporter(self.fp,ensure_ascii=False, encoding="utf-8")
def process_item(self, item, spider):
self.exporters.export_item(item) # 输出数据
return item
def close_spider(self,spider):
self.fp.close() # 爬虫结束后,关闭文件
import scrapy
class WxappItem(scrapy.Item): # 定义容器类
title = scrapy.Field()
author = scrapy.Field()
time = scrapy.Field()
content = scrapy.Field()
参考链接:https://blog.csdn.net/weixin_42122125/article/details/105556273.
发布日期:2020年4月17日
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。