【发布时间】:2019-11-17 11:25:27
【问题描述】:
我想根据搜索的字词从 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
【问题讨论】:
-
假设谷歌新闻类名称保持不变是个好主意吗?
-
总是一样的。
标签: python web-scraping beautifulsoup