(详细步骤)使用scrapy爬取新浪热点新闻,进入链接获取新闻内容。

本文主要是介绍(详细步骤)使用scrapy爬取新浪热点新闻,进入链接获取新闻内容。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.在Pycharm的Terminal中输入“scrapy startproject news”创建爬虫项目,“news”为项目名。

2.自动生成的工程目录

3.编写item.py,也就是定义要爬取信息的字段

4.进入news/news/spiders目录下,使用命令“  scrapy genspider -t crawl newscrawl ‘news.sina.com.cn’  ”创建爬虫名为“newscrawl”的爬虫文件,爬虫域是“news.sina.com.cn”。

5.编写newscrawl.py文件。其中“https://news.sina.com.cn/\w/time/\w+-\w+.shtml”正则是用来匹配“http://news.sina.com.cn/hotnews/”页面上的链接的。注:可以查看链接的规律个性化定制。

xpath的匹配可以通过“xpath helper”插件来快速定位,或者通过chrome浏览器按F12检查网页代码,选中匹配的代码右击选择“copy xpath”获取匹配规则。

 

6.编写pipelines.py文件,处理爬取的数据。(此处是存入数据库)

7.在settings.py中将下图中的代码注释取消。

8.启动爬虫,在spiders目录下启动爬虫“scrapy crawl newscrawl

9.任务结束后查看数据库。(因为数据库中newsContent字段在自己的项目中是用富文本编辑器展示的,所以将标签和内容一起爬取出来,便于展示。可以根据自己的需求在步骤5中修改content的xpath匹配规则)

10.将项目部署到阿里云,设置定时任务。

链接:跳转至“定时爬虫”

代码附录: 

1.newscrawl.py

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from news.items import NewsItem
import timeclass NewscrawlSpider(CrawlSpider):name = 'newscrawl'allowed_domains = ['news.sina.com.cn']start_urls = ['http://news.sina.com.cn/hotnews/']now_time = time.strftime("%Y-%m-%d", time.localtime())reg = r"https://news.sina.com.cn/\w/time/\w+-\w+.shtml"reg = reg.replace("time", now_time)rules = (# Rule(LinkExtractor(allow=r'news.sina.com.cn/hotnews/')),Rule(LinkExtractor(allow=reg), callback='parse_item', follow=True),)def parse_item(self, response):item = NewsItem()item["title"] = response.xpath('//div[@class="main-content w1240"]/h1/text()').extract()[0]item["content"] = response.xpath('//div[@class="article"]').extract()[0]item["source"] = response.xpath('//*[@id="top_bar"]//div[@class="date-source"]/a/text()').extract()[0]item["date"] = response.xpath('//*[@id="top_bar"]//div[@class="date-source"]/span/text()').extract()[0]return item

2. items.py

# -*- coding: utf-8 -*-# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass NewsItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()title = scrapy.Field()content = scrapy.Field()source = scrapy.Field()date = scrapy.Field()

3. pipelines.py

# -*- coding: utf-8 -*-# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html# 本地测试
# import json
#
# class NewsPipeline(object):
#     def __init__(self):
#         # 创建一个文件,将文件的保存类型设置为utf-8
#         self.filename = open("news1.json", "w", encoding="utf-8")
#     def process_item(self, item, spider):
#         # 将数据由列表格式先变换为字典格式,再变换为json格式的数据
#         text = json.dumps(dict(item), ensure_ascii=False)+"\n"
#         # 保存数据为utf-8的格式
#         self.filename.write(text)
#         return itemimport pymysqlclass NewsPipeline(object):def __init__(self):# 连接MySQL数据库self.connect = pymysql.connect(host='服务器ip地址', user='root', password='******', db='news', port=3306)self.cursor = self.connect.cursor()def process_item(self, item, spider):# 往数据库里面写入数据sql = "insert into t_news(newsTitle, newsContent, newsSource, newsDate) values (%s, %s, %s, %s)"self.cursor.execute(sql, (item['title'], item['content'], item['source'], item['date']))self.connect.commit()return item# 关闭数据库def close_spider(self, spider):self.cursor.close()self.connect.close()

 

 

这篇关于(详细步骤)使用scrapy爬取新浪热点新闻,进入链接获取新闻内容。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/327963

相关文章

Windows环境下解决Matplotlib中文字体显示问题的详细教程

《Windows环境下解决Matplotlib中文字体显示问题的详细教程》本文详细介绍了在Windows下解决Matplotlib中文显示问题的方法,包括安装字体、更新缓存、配置文件设置及编码調整,并... 目录引言问题分析解决方案详解1. 检查系统已安装字体2. 手动添加中文字体(以SimHei为例)步骤

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析(结合应用场景)

《nginx-t、nginx-sstop和nginx-sreload命令的详细解析(结合应用场景)》本文解析Nginx的-t、-sstop、-sreload命令,分别用于配置语法检... 以下是关于 nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析,结合实际应

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

C#连接SQL server数据库命令的基本步骤

《C#连接SQLserver数据库命令的基本步骤》文章讲解了连接SQLServer数据库的步骤,包括引入命名空间、构建连接字符串、使用SqlConnection和SqlCommand执行SQL操作,... 目录建议配合使用:如何下载和安装SQL server数据库-CSDN博客1. 引入必要的命名空间2.

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome