python-3.x - 我想打开在谷歌上搜索时出现的第一个链接
问题描述
我想从 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')
解决方案
问题是当您未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&hl=et" onmousedown="return rwt(this,'','','','1','AOvVaw2lWnw7oOhIzXdoFGYhvwv_','','2ahUKEwjove3h7onkAhXmkYsKHbWPAUYQFjAAegQIBhAC','','',event)"><h3 class="LC20lb">
... and so on.
推荐阅读
- python - 在熊猫中添加基于多个条件的新数据框
- javascript - 随着数据添加到 Firebase,数组的元素会增加。我该如何预防?
- css - SVG 线性渐变填充适用于桌面视图,但不适用于移动设备。我怎样才能解决这个问题?
- javafx - 即使未处于编辑状态,JavaFx 11 ListView 也会消耗 ESCAPE 按键事件
- github - 合并两个 PR
- c# - System.Net.WebSockets 连接在服务器侦听之前打开
- javascript - NodeJS 事件循环中的 process.nextTick() 何时被调用?
- python - 使用 ytmusicapi 获取 YouTube 音乐库上传列表
- coq - 教 Coq 自然数结合律成立
- javascript - 具有可变最大值的范围滑块