如何使用Python和BeautifulSoup抓取多个Google页面

背后

我写了一个可以抓取Google新闻搜索结果的代码。但是它总是只刮首页。如何编写一个循环,使我可以抓取前2,3 ... n页?

我知道在In中,url我需要为page添加参数,并将其全部放入中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')

另外,可以将forgoogle news和pages的这种逻辑应用于例如bing newsyahoo news,我的意思是,我可以使用相同的参数还是url不同的参数

昆杜克

我认为您需要更改您的网址。尝试以下代码,看看是否可行。

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'
page=0


while True:
    url = 'https://www.google.com/search?q={}&tbm=nws&sxsrf=ACYBGNTx2Ew_5d5HsCvjwDoo5SC4U6JBVg:1574261023484&ei=H1HVXf-fHfiU1fAP65K6uAU&start={}&sa=N&ved=0ahUKEwi_q9qog_nlAhV4ShUIHWuJDlcQ8tMDCF8&biw=1280&bih=561&dpr=1.5'.format(term,page)
    print(url)

    response = requests.get(url, headers=headers,verify=False)
    if response.status_code!=200:
        break
    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')
    page=page+10

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用不变的网址抓取多个页面-Python 3

使用BeautifulSoup和Python刮取多个页面

如何使用python和beautifulsoup4循环抓取网站中多个页面的数据

如何使用BeautifulSoup和Python抓取页面?

如何在一个Web上从多个页面抓取数据,我正在使用Python和BeautifulSoup

如何使用Selenium(Python)网页抓取多个页面

如何使用BeautifulSoup从页面抓取

使用Python和BeautifulSoup从HTML抓取数字

Web使用BeautifulSoup抓取多个页面

使用python和BeautifulSoup进行网络抓取

如何使用BeautifulSoup创建循环以从源URL抓取多个页面?

Python-使用BeautifulSoup在页面内抓取多个类

python beautifulsoup抓取存档页面

使用 Beautifulsoup 和 Python 抓取复杂的表格

使用python为多个页面抓取网页

使用 BeautifulSoup 和 Python 抓取多个表格页面

如何使用python BeautifulSoup通过分页抓取页面

使用 Python 和 BeautifulSoup 抓取 alt 标签

如何使用 Python BeautifulSoup 抓取 ID

Python - 使用 BeautifulSoup 和 Urllib 进行抓取

BeautifulSoup 无法抓取多个页面

使用 BeautifulSoup 在 python 中抓取多个页面

使用 BeautifulSoup 和 Python 抓取表格

使用 BeautifulSoup 从多个页面下载多线程文件的网页抓取

如何从python和beautifulsoup中的页面抓取iframe数据范围

如何使用 CrawlSpider 抓取多个 json 页面?

如何使用 Python 和 BeautifulSoup 从 html 表中抓取数据?

使用 BeautifulSoup 在 Steam 中抓取多个页面

使用 Python 和 BeautifulSoup 进行问题抓取