scrapy分页抓取网页( Java开发之scrapy框架(一):日期,热度和ID)
优采云 发布时间: 2021-10-26 07:11scrapy分页抓取网页(
Java开发之scrapy框架(一):日期,热度和ID)
4、日期、人气和ID
5、程序运行图
三、具体开发
1、任务要求
1.爬取文章及网易、搜狐、凤凰、澎湃的评论网站及评论
2.新闻页数不低于10万页
3.每个新闻页面及其评论可在1天内更新
2、功能设计
1. 设计一个可以抓取指定网站的所有页面的网络爬虫,并提取文章和评论内容
2. 定期运行网络爬虫,每天更新数据
3、系统架构
先简单介绍下scrapy框架,它是一个爬虫框架
绿线是数据流向,
(1)首先从初始URL开始,Scheduler会交给Downloader下载,
(2)下载后交给Spider分析,这里的Spider是爬虫的核心功能代码
(3)Spider对结果的分析有两种方式:一种是需要进一步爬取的链接,通过中间件返回给Scheduler;另一种是需要保存的数据,发送到ItemPipeline,处理和存储
(4)最后输出所有数据并保存为文件
4、实际项目
(1)项目结构
可以看到,NewsSpider-master是一个完整的项目文件夹,下面存放着每个网站对应的爬虫启动脚本debug_xx.py。 scrapyspider文件夹存放scrapy框架需要的相关文件,spiders文件夹存放实际爬虫代码
(2)爬虫引擎
以网易新闻的爬虫news_163.py为例,简单说明部分核心代码:
①定义爬虫类:
class news163_Spider(CrawlSpider):
# 网易新闻爬虫名称
name = "163news"
# 伪装成浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',
}
#网易全网
allowed_domains = [
"163.com"
]
#新闻版
start_urls = [
'http://news.163.com/'
]
#正则表达式表示可以继续访问的url规则,http://news.163.com/\d\d\d\d\d(/([\w\._+-])*)*$
rules = [
Rule(LinkExtractor(
allow=(
('http://news\.163\.com/.*$')
),
deny = ('http://.*.163.com/photo.*$')
),
callback="parse_item",
follow=True)
]
②网页内容分析模块
根据不同内容的Xpath路径从页面中提取内容。由于网站不同时期的页面结构不同,根据不同的页面布局分为几个if判断语句块;
def parse_item(self, response):
# response是当前url的响应
article = Selector(response)
article_url = response.url
global count
# 分析网页类型
# 比较新的网易新闻 http://news.163.com/05-17/
if get_category(article) == 1:
articleXpath = '//*[@id="epContentLeft"]'
if article.xpath(articleXpath):
titleXpath = '//*[@id="epContentLeft"]/h1/text()'
dateXpath = '//*[@id="epContentLeft"]/div[1]/text()'
contentXpath = '//*[@id="endText"]'
news_infoXpath ='//*[@id="post_comment_area"]/script[3]/text()'
# 标题
if article.xpath(titleXpath):
news_item = newsItem()
news_item['url'] = article_url
get_title(article, titleXpath, news_item)
# 日期
if article.xpath(dateXpath):
get_date(article, dateXpath, news_item)
# 内容
if article.xpath(contentXpath):
get_content(article, contentXpath, news_item)
count = count + 1
news_item['id'] = count
# 评论
try:
comment_url = get_comment_url(article, news_infoXpath)
# 评论处理
comments = get_comment(comment_url, news_item)[1]
news_item['comments'] = comments
except:
news_item['comments'] = ' '
news_item['heat'] = 0
yield news_item
根据正则表达式匹配页面内容中的日期信息:
'''通用日期处理函数'''
def get_date(article, dateXpath, news_item):
# 时间
try:
article_date = article.xpath(dateXpath).extract()[0]
pattern = re.compile("(\d.*\d)") # 正则匹配新闻时间
article_datetime = pattern.findall(article_date)[0]
#article_datetime = datetime.datetime.strptime(article_datetime, "%Y-%m-%d %H:%M:%S")
news_item['date'] = article_datetime
except:
news_item['date'] = '2010-10-01 17:00:00'
其他功能:
'''网站分类函数'''
def get_category(article):
'''字符过滤函数'''
def str_replace(content):
'''通用正文处理函数'''
def get_content(article, contentXpath, news_item):
'''评论信息提取函数'''
def get_comment_url(article, news_infoXpath):
'''评论处理函数'''
def get_comment(comment_url, news_item):
(3)运行爬虫并格式化存储
①在settings.py中配置
import sys
# 这里改成爬虫项目的绝对路径,防止出现路径搜索的bug
sys.path.append('E:\Python\以前的项目\\NewsSpider-master\scrapyspider')
# 爬虫名称
BOT_NAME = 'scrapyspider'
# 设置是否服从网站的爬虫规则
ROBOTSTXT_OBEY = True
# 同时并发请求数,越大则爬取越快同时负载也大
CONCURRENT_REQUESTS = 32
#禁止cookies,防止被ban
COOKIES_ENABLED = False
# 输出的编码格式,由于Excel默认是ANSI编码,所以这里保持一致
# 如果有其他编码需求如utf-8等可自行更改
FEED_EXPORT_ENCODING = 'ANSI'
# 增加爬取延迟,降低被爬网站服务器压力
DOWNLOAD_DELAY = 0.01
# 爬取的新闻条数上限
CLOSESPIDER_ITEMCOUNT = 500
# 下载超时设定,超过10秒没响应则放弃当前URL
DOWNLOAD_TIMEOUT = 100
ITEM_PIPELINES = {
'scrapyspider.pipelines.ScrapyspiderPipeline': 300,# pipeline中的类名
}
②运行爬虫,保存新闻内容
抓取到的新闻内容和评论需要进行格式化和存储。如果在IDE中运行调试脚本,效果如下:
抓取后会保存为.csv文件,用Excel打开即可查看:
③如果需要单独提取评论,可以使用csv_process.py,效果如下:
四、其他补充
目前不可用