1、创建一个scrapy项目
scrapy startproject sunPro
cd sunPro
scrapy genspider -t crawl sun www.xxxx.com
2、配置文件(settings.py)修改
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = "'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.197.400 QQBrowser/11.6.5265.400'"
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
LOG_LEVEL = 'ERROR'
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
"essays.pipelines.EssaysPipeline": 300,
}
3、代码部分
3.1 items.py如下,
import scrapy
class SunproItem(scrapy.Item):
# define the fields for your item here like:
title = scrapy.Field()
new_num = scrapy.Field()
new_state = scrapy.Field()
new_datetime = scrapy.Field()
class DetailItem(scrapy.Item):
content = scrapy.Field()
3.2 sun.py如下,
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from sunPro.items import SunproItem,DetailItem
#需求:爬取sun网站中的编号,新闻标题,新闻内容,标号
class SunSpider(CrawlSpider):
name = 'sun'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://wz.sun0769.com/political/index/politicsNewest?id=1&page=1']
#链接提取器:根据指定规则(allow="正则")进行指定链接的提取
link = LinkExtractor(allow=r'id=1&page=\d+')
link_detail = LinkExtractor(allow=r'id=\d+')
rules = (
#规则解析器:将链接提取器提取到的链接进行指定规则(callback)的解析操作
Rule(link, callback='parse_item', follow=True),
#follow=True:可以将链接提取器 继续作用到 连接提取器提取到的链接 所对应的页面中
Rule(link_detail,callback='parse_detail')
)
#http://wz.sun0769.com/html/question/201907/421001.shtml
#http://wz.sun0769.com/html/question/201907/420987.shtml
#解析新闻编号和新闻的标题,以及状态和时间
#如下两个解析方法中是不可以实现请求传参!
#如法将两个解析方法解析的数据存储到同一个item中,可以以此存储到两个item
def parse_item(self, response):
#注意:xpath表达式中不可以出现tbody标签
tr_list = response.xpath('/html/body/div[2]/div[3]/ul[2]/li')
for tr in tr_list:
new_num = tr.xpath('./span[1]/text()').extract_first()
new_state = tr.xpath('./span[2]/text()').extract_first()
new_title = tr.xpath('./span[3]/a/text()').extract_first()
new_datetime = tr.xpath('./span[5]/text()').extract_first()
item = SunproItem()
item['title'] = new_title
item['new_num'] = new_num
item['new_state'] = new_state
item['new_datetime'] = new_datetime
yield item
#解析新闻内容
def parse_detail(self,response):
new_content = response.xpath('/html/body/div[3]/div[2]/div[2]/div[2]/pre/text()').extract()
new_content = ''.join(new_content)
# print(new_id,new_content)
item = DetailItem()
item['content'] = new_content
yield item
3.3 pipelines.py如下,
class SunproPipeline(object):
fp = None
def open_spider(self, spider):
self.fp = open('./news.txt', 'w+', encoding='utf-8')
print('正在爬取文件...')
def process_item(self, item, spider):
# 如何判定item的类型
# 将数据写入数据库时,如何保证数据的一致性
if item.__class__.__name__ == 'DetailItem':
self.fp.write('内容:', item['content'])
else:
self.fp.write('编号:', item['new_num'], '标题:',item['title'], '状态:',item['new_state'], '受理时间:',item['new_datetime'])
print(item['new_num'], item['title'], item['new_state'], item['new_datetime'])
return item
def close_spider(self, spider):
self.fp.close()
print('新闻爬取完毕...')