脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现Scrapy爬取网易新闻

python实现Scrapy爬取网易新闻

2021-09-26 00:33后端码匠 Python

这篇文章主要介绍了python实现Scrapy爬取网易新闻,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1. 新建项目

在命令行窗口下输入scrapy startproject scrapytest, 如下

python实现Scrapy爬取网易新闻

然后就自动创建了相应的文件,如下

python实现Scrapy爬取网易新闻

2. 修改itmes.py文件

打开scrapy框架自动创建的items.py文件,如下

  1. # Define here the models for your scraped items
  2. #
  3. # See documentation in:
  4. # https://docs.scrapy.org/en/latest/topics/items.html
  5.  
  6. import scrapy
  7.  
  8. class ScrapytestItem(scrapy.Item):
  9. # define the fields for your item here like:
  10. # name = scrapy.Field()
  11. pass

编写里面的代码,确定我要获取的信息,比如新闻标题,url,时间,来源,来源的url,新闻的内容等

  1. class ScrapytestItem(scrapy.Item):
  2. # define the fields for your item here like:
  3. # name = scrapy.Field()
  4.  
  5. title = scrapy.Field()
  6. timestamp = scrapy.Field()
  7. category = scrapy.Field()
  8. content = scrapy.Field()
  9. url = scrapy.Field()
  10.  
  11. pass

3. 定义spider,创建一个爬虫模板

3.1 创建crawl爬虫模板

在命令行窗口下面 创建一个crawl爬虫模板(注意在文件的根目录下面,指令检查别输入错误,-t 表示使用后面的crawl模板),会在spider文件夹生成一个news163.py文件

  1. scrapy genspider -t crawl codingce news.163.com

然后看一下这个‘crawl'模板和一般的模板有什么区别,多了链接提取器还有一些爬虫规则,这样就有利于我们做一些深度信息的爬取

  1. import scrapy
  2. from scrapy.linkextractors import LinkExtractor
  3. from scrapy.spiders import CrawlSpider, Rule
  4.  
  5. class CodingceSpider(CrawlSpider):
  6. name = 'codingce'
  7. allowed_domains = ['163.com']
  8. start_urls = ['http://news.163.com/']
  9.  
  10. rules = (
  11. Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
  12. )
  13.  
  14. def parse_item(self, response):
  15. item = {}
  16. #item['domain_id'] = response.xpath('//input[@id="sid"]/@value').get()
  17. #item['name'] = response.xpath('//div[@id="name"]').get()
  18. #item['description'] = response.xpath('//div[@id="description"]').get()
  19. return item

3.2 补充知识:selectors选择器

支持xpath和css,xpath语法如下

  1. /html/head/title
  2.  
  3. /html/head/title/text()
  4.  
  5. //td (深度提取的话就是两个/)
  6.  
  7. //div[@class=‘mine']

3.3. 分析网页内容

在谷歌chrome浏览器下,打在网页新闻的网站,选择查看源代码,确认我们可以获取到itmes.py文件的内容(其实那里面的要获取的就是查看了网页源代码之后确定可以获取的)

确认标题、时间、url、来源url和内容可以通过检查和标签对应上,比如正文部分

主体

python实现Scrapy爬取网易新闻

标题

python实现Scrapy爬取网易新闻

时间

python实现Scrapy爬取网易新闻

分类

python实现Scrapy爬取网易新闻

4. 修改spider下创建的爬虫文件

4.1 导入包

打开创建的爬虫模板,进行代码的编写,除了导入系统自动创建的三个库,我们还需要导入news.items(这里就涉及到了包的概念了,最开始说的–init–.py文件存在说明这个文件夹就是一个包可以直接导入,不需要安装)

注意:使用的类ExampleSpider一定要继承自CrawlSpider,因为最开始我们创建的就是一个‘crawl'的爬虫模板,对应上

  1. import scrapy
  2. from scrapy.linkextractors import LinkExtractor
  3. from scrapy.spiders import CrawlSpider, Rule
  4. from scrapytest.items import ScrapytestItem
  5.  
  6. class CodingceSpider(CrawlSpider):
  7. name = 'codingce'
  8. allowed_domains = ['163.com']
  9.  
  10. start_urls = ['http://news.163.com/']
  11.  
  12. rules = (
  13. Rule(LinkExtractor(allow=r'.*\.163\.com/\d{2}/\d{4}/\d{2}/.*\.html'), callback='parse', follow=True),
  14. )
  15.  
  16. def parse(self, response):
  17. item = {}
  18. content = '<br>'.join(response.css('.post_content p::text').getall())
  19. if len(content) < 100:
  20. return
  21.  
  22. return item

Rule(LinkExtractor(allow=r'..163.com/\d{2}/\d{4}/\d{2}/..html'), callback=‘parse', follow=True), 其中第一个allow里面是书写正则表达式的(也是我们核心要输入的内容),第二个是回调函数,第三个表示是否允许深入

最终代码

  1. from datetime import datetime
  2. import re
  3.  
  4. import scrapy
  5. from scrapy.linkextractors import LinkExtractor
  6. from scrapy.spiders import CrawlSpider, Rule
  7. from scrapytest.items import ScrapytestItem
  8.  
  9. class CodingceSpider(CrawlSpider):
  10. name = 'codingce'
  11. allowed_domains = ['163.com']
  12.  
  13. start_urls = ['http://news.163.com/']
  14.  
  15. rules = (
  16. Rule(LinkExtractor(allow=r'.*\.163\.com/\d{2}/\d{4}/\d{2}/.*\.html'), callback='parse', follow=True),
  17. )
  18.  
  19. def parse(self, response):
  20. item = {}
  21. content = '<br>'.join(response.css('.post_content p::text').getall())
  22. if len(content) < 100:
  23. return
  24.  
  25. title = response.css('h1::text').get()
  26.  
  27. category = response.css('.post_crumb a::text').getall()[-1]
  28. print(category, "=======category")
  29. time_text = response.css('.post_info::text').get()
  30. timestamp_text = re.search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', time_text).group()
  31. timestamp = datetime.fromisoformat(timestamp_text)
  32. print(title, "=========title")
  33. print(content, "===============content")
  34. print(timestamp, "==============timestamp")
  35. print(response.url)
  36. return item

python实现Scrapy爬取网易新闻

到此这篇关于python实现Scrapy爬取网易新闻的文章就介绍到这了,更多相关python Scrapy爬取网易新闻内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_43874301/article/details/115009135

延伸 · 阅读

精彩推荐