繁体   English   中英

从 Python 和 BeautifulSoup 中的搜索结果中抓取网址

[英]Scrape urls from search results in Python and BeautifulSoup

我试图从搜索结果中抓取一些 url,并尝试将 cookies 设置或用户代理包括为 Mozilla/5.0 等。 我仍然无法从搜索结果中获取任何网址。 我可以使用任何解决方案吗?

from bs4 import BeautifulSoup
import requests

monitored_tickers = ['GME', 'TSLA', 'BTC']

def search_for_stock_news_urls(ticker):
    search_url = "https://www.google.com/search?q=yahoo+finance+{}&tbm=nws".format(ticker)
    r = requests.get(search_url)
    soup = BeautifulSoup(r.text, 'html.parser')
    atags = soup.find_all('a')
    hrefs = [link['href'] for link in atags]
    return hrefs

raw_urls = {ticker:search_for_stock_news_urls(ticker) for ticker in monitored_tickers}
raw_urls

您可能会遇到 requests 和 bs4 可能不是您要完成的任务的最佳工具的问题。 正如 balderman 在另一条评论中所说,使用谷歌搜索 api 会更容易。

这段代码:

from googlesearch import search

tickers = ['GME', 'TSLA', 'BTC']
links_list = []
for ticker in tickers:
    ticker_links = search(ticker, stop=25)
    links_list.append(ticker_links)

将为每个自动收报机列出谷歌上排名前 25 的链接,并将 append 列出到另一个列表中。 Yahoo finance 肯定会在该链接列表中,基于关键字的简单解析器将为该特定代码获取 yahoo finance url。 您还可以将 search() function 中的搜索条件调整为您想要的任何内容,例如说 ticker + 'yahoo finance'。

谷歌新闻可以很容易地通过requestsbeautifulsoup被抓取。 使用user-agent从那里提取数据就足够了。

查看SelectorGadget Chrome 扩展程序,通过单击要提取的元素来直观地获取CSS选择器。

如果您只想从 Google 新闻中提取 URL,那么它很简单:

for result in soup.select('.dbsr'):
    link = result.a['href']
# 10 links here..

在线 IDE 中更多抓取的代码和示例

from bs4 import BeautifulSoup
import requests, lxml

headers = {
    "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}

params = {
    "q": "yahoo finance BTC",
    "hl": "en",
    "gl": "us",
    "tbm": "nws",
}

html = requests.get('https://www.google.com/search', headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')

for result in soup.select('.dbsr'):
    link = result.a['href']
    print(link)

-----
'''
https://finance.yahoo.com/news/riot-blockchain-reports-record-second-203000136.html
https://finance.yahoo.com/news/el-salvador-not-require-bitcoin-175818038.html
https://finance.yahoo.com/video/bitcoin-hovers-around-50k-paypal-155437774.html
... other links
'''

或者,您可以使用来自 SerpApi 的Google 新闻结果 API获得相同的结果。 这是带有免费计划的付费 API。

不同之处在于您不必弄清楚如何提取元素、随着时间的推移维护解析器、绕过 Google 的阻止。

集成代码:

import os
from serpapi import GoogleSearch

params = {
  "engine": "google",
  "q": "coca cola",
  "tbm": "nws",
  "api_key": os.getenv("API_KEY"),
}

search = GoogleSearch(params)
results = search.get_dict()

for news_result in results["news_results"]:
  print(f"Title: {news_result['title']}\nLink: {news_result['link']}\n")

-----
'''
Title: Coca-Cola Co. stock falls Monday, underperforms market
Link: https://www.marketwatch.com/story/coca-cola-co-stock-falls-monday-underperforms-market-01629752653-994caec748bb
... more results
'''

PS 我写了 一篇博文,内容是关于如何通过视觉呈现以更详细的方式抓取 Google 新闻(包括分页)。

免责声明,我为 SerpApi 工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM