首页 > 解决方案 > 使用 BS4 找不到 Google 搜索的结果 - Python

问题描述

我试图从谷歌搜索中取回股票价格,但 BS4 的结果超过 300 行。

在此处输入图像描述

这是我的代码:

import bs4, requests

exampleFile = requests.get('https://www.google.com/search?q=unip6')
exampleSoup = bs4.BeautifulSoup(exampleFile.text, features="html.parser")
elems = exampleSoup.select('div', {"class": 'IsqQVc NprOob'})
print(len(elems))
for each in elems:
    print(each.getText())
    print(each.attrs)
    print('')

我希望结果只是价格:'23,85'

标签: pythonbeautifulsoup

解决方案


在这种情况下,页面不是动态加载的,因此可以在汤中找到目标详细信息。通过不使用类选择器,也可以避免更改类名的问题(至少暂时......):

for s in soup.select("div"):
    if 'Latest Trade' in s.text:
        print(s.text.split('Latest Trade. ')[1].split('BRL')[0])
        break

输出:

23.85

推荐阅读