首页 > 解决方案 > 我想打开在谷歌上搜索时出现的第一个链接

问题描述

我想从 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.xbeautifulsoupweb-crawler

解决方案


问题是当您未User-Agent在标题中指定时,谷歌会提供不同的 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.

推荐阅读