【发布时间】:2023-03-20 02:03:01
【问题描述】:
我写了一个可以抓取谷歌新闻搜索结果的代码。但它总是只刮第一页。 如何编写一个允许我抓取前 2,3...n 页的循环?
我知道在url中需要为页面添加参数,并全部放入for loop,但不知道怎么做?
此代码为我提供了第一个搜索页面的标题、段落和日期:
from bs4 import BeautifulSoup
import requests
headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
term = 'usa'
url = 'https://www.google.com/search?q={0}&source=lnms&tbm=nws'.format(term)# i know that I need to add this parameter for page, but I do not know how
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
headline_text = soup.find_all('h3', class_= "r dO0Ag")
snippet_text = soup.find_all('div', class_='st')
news_date = soup.find_all('div', class_='slp')
另外,google news 和页面的这个逻辑可以应用于例如bing news 或yahoo news,我的意思是,我可以使用相同的参数还是url 不同?
【问题讨论】:
-
小心,因为google有一些强大的防刮措施,你可能会被屏蔽。如果您不想开发非常安全的抓取工具(IP 轮换、人体移动复制等),您可以考虑使用 Google 的 API 之一来获取您的数据
-
你可以做
url = 'https://www.google.com/search?q={0}&source=lnms&tbm=nws&page={1}'.format(term,page)看看stackoverflow.com/questions/38635419/… -
我试过了,但它总是返回我的第一页,我可以为页面输入任何数字,它总是返回我第 1 页的内容
标签: python beautifulsoup