首页 > 解决方案 > 使用 Python 和 Beautiful Soup 抓取 Google 新闻结果只检索没有标题的第一页

问题描述

我想根据搜索的字词从 Google 新闻搜索页面中抓取标题和段落文本。我想对前n页执行此操作。

我写了一段代码只用于抓取第一页,但我不知道如何修改我的url,以便我可以转到其他页面(第 2、3 ...)。这是我遇到的第一个问题

第二个问题是我不知道如何抓取头条新闻。它总是给我返回空列表。我尝试了多种解决方案,但它总是返回空列表。(我不认为该页面是动态的)。

另一方面,在标题下方抓取段落文本效果很好。你能告诉我如何解决这两个问题吗?

这是我的代码:

from bs4 import BeautifulSoup
import requests

term = 'cocacola'

# this is only for page 1, how to go to page 2?
url = 'https://www.google.com/search?q={0}&source=lnms&tbm=nws'.format(term)

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# I think that this is not javascipt sensitive, its not dynamic            
headline_results = soup.find_all('a', class_="l lLrAF")
#headline_results = soup.find_all('h3', class_="r dO0Ag") # also does not work
print(headline_results) #empty list, IDK why?

paragraph_results = soup.find_all('div', class_='st')
print(paragraph_results) # works

标签: pythonweb-scrapingbeautifulsoup

解决方案


问题一:翻页。

为了移动到下一页,您需要start在 URL 格式的字符串中包含关键字:

term = 'cocacola'
page = 2
url = 'https://www.google.com/search?q={}&source=lnms&tbm=nws&start={}'.format(
    term, (page - 1) * 10
)

问题二:刮掉头条。

Google 会重新生成 DOM 元素的类名称、id 等,因此每次检索一些新的未缓存信息时,您的方法都可能会失败。


推荐阅读