【问题标题】:I want to open the first link that appear when i do a search on google我想打开在谷歌上搜索时出现的第一个链接
【发布时间】:2019-08-17 11:53:19
【问题描述】:

我想从 html 解析器获取第一个链接,但我得到了任何东西(试图打印)。 此外,当我在浏览器上检查页面时,链接位于 class='r' 但是当我打印 soup.prettify() 并仔细分析时,我发现没有 class='r',而是 class="BNeawe UPmit AP7Wnd"。 请帮忙,提前谢谢!

import requests
import sys
import bs4
import webbrowser


def open_web(query):
    res = requests.get('https://google.com/search?q=' + query)
    res.raise_for_status()

    soup = bs4.BeautifulSoup(res.text, "html.parser")
    link_elements = soup.select('.r a')
    link_to_open = min(1, len(link_elements))
    for i in range(link_to_open):
        webbrowser.open('https://google.com' + link_elements[i].get('href'))


open_web('youtube')

【问题讨论】:

    标签: python-3.x beautifulsoup web-crawler


    【解决方案1】:

    问题在于,当您未在标题中指定 User-Agent 时,Google 会提供不同的 HTML。要将User-Agent 添加到您的请求中,请将其放在headers= 属性中:

    import requests
    import bs4
    
    def open_web(query):
        headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0'}
    
        res = requests.get('https://google.com/search?q=' + query, headers=headers)
        res.raise_for_status()
    
        soup = bs4.BeautifulSoup(res.text, "html.parser")
        link_elements = soup.select('.r a')
        print(link_elements)
    
    open_web('youtube')
    

    打印:

    [<a href="https://www.youtube.com/?gl=EE&amp;hl=et" onmousedown="return rwt(this,'','','','1','AOvVaw2lWnw7oOhIzXdoFGYhvwv_','','2ahUKEwjove3h7onkAhXmkYsKHbWPAUYQFjAAegQIBhAC','','',event)"><h3 class="LC20lb"> 
    
    ... and so on.
    

    【讨论】:

    • 嘿,非常感谢。但是,你能告诉我如何知道我应该为我的标题分配什么值吗?
    • @TarunSharma 要从 Google 获取正确的 HTML,只需在标题中指定 User-Agent
    【解决方案2】:

    您收到了一个完全不同的 HTML,其中包含不同的元素和选择器,因此输出为空。谷歌阻止你的请求的原因是因为默认的requests user-agentpython-requests 并且谷歌理解它并阻止它。 Check what's your user-agent.

    User-agent 让我们识别浏览器、它的版本号和它的主机操作系统,它在 Web 上下文中代表一个人(浏览器),让服务器和网络对等方识别它是否是机器人。

    有时您可以收到带有不同选择器的不同 HTML。


    您可以将 URL 参数作为dict() 传递,这样更具可读性,并且请求会自动为您完成所有操作(将user-agent 添加到headers 中也是如此):

    params = {
      "q": "My query goes here"
    }
    
    requests.get("YOUR_URL", params=params)
    

    如果您想获得第一个链接,请改用select_one()


    代码和full example in the online IDE

    from bs4 import BeautifulSoup
    import requests
    
    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": "My query goes here"
    }
    
    html = requests.get('https://www.google.com/search', headers=headers, params=params)
    soup = BeautifulSoup(html.text, 'lxml')
    
    link = soup.select_one('.yuRUbf a')['href']
        print(link)
    
    # https://dev.mysql.com/doc/refman/8.0/en/entering-queries.html
    

    或者,您可以使用来自 SerpApi 的 Google Organic Results API 来做同样的事情。这是一个带有免费计划的付费 API。

    您的情况不同的是,您只需要从 JSON 字符串中提取所需的数据,而不是弄清楚如何从 Google 提取、维护或绕过块。

    要集成的代码:

    import os
    from serpapi import GoogleSearch
    
    params = {
        "engine": "google",
        "q": "My query goes here",
        "hl": "en",
        "api_key": os.getenv("API_KEY"),
    }
    
    search = GoogleSearch(params)
    results = search.get_dict()
    
    # [0] means first index of search results
    link = results['organic_results'][0]['link']
    
    # https://dev.mysql.com/doc/refman/8.0/en/entering-queries.html
    

    免责声明,我为 SerpApi 工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-25
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      相关资源
      最近更新 更多