首页 > 解决方案 > How do I grab the headline titles from the Google News webpage with Scrapy?

问题描述

I saved an offline file of https://news.google.com/search?q=amazon&hl=en-US&gl=US&ceid=US%3Aen

Having trouble determining how to grab the titles of the listed articles.

import scrapy

class newsSpider(scrapy.Spider):
    name = "news"
    start_urls = ['file:///127.0.0.1/home/toni/Desktop/crawldeez/googlenewsoffline.html/'
                  ]

    def parse(self, response):
        for xrnccd in response.css('a.MQsxIb.xTewfe.R7GTQ.keNKEd.j7vNaf.Cc0Z5d.EjqUne'):
            yield {
                'ipQwMb.ekueJc.RD0gLb': xrnccd.css('h3.ipQwMb.ekueJc.RD0gLb::ipQwMb.ekueJc.RD0gLb').get(),
            }

标签: scrapygoogle-news

解决方案


问题似乎在于页面内容是使用 JavaScript 动态呈现的,因此无法使用cssorxpath方法从 HTML 中提取。但是,它存在于响应正文中,因此您可以使用正则表达式提取它。这是Scrapy shell会话,展示了如何:

$ scrapy shell "https://news.google.com/search?q=amazon&hl=en-US&gl=US&ceid=US%3Aen"
...
>>> import re
>>> from pprint import pprint
>>>
>>> titles = re.findall(r'<h3 class="[^"]+?"><a[^>]+?>(.+?)</a>', response.text)
>>> pprint(titles)
['Amazon will no longer sell Chinese goods in China',
 'YouTube is finally coming back to Amazon’s Fire TV devices',
 'Amazon Plans to Use Digital Media to Expand Its Advertising Business',
 'Amazon flooded with fake reviews; Learn how to spot them',
 'How To Win in Today&#39;s Amazon World',
 'Amazon Day: How to schedule Amazon deliveries',
 'Bezos Disputes Amazon’s Market Power. But His Merchants Feel the Pinch',
 '20 Best Action Movies to Stream on Amazon Prime',
 ...]

推荐阅读