首页 > 解决方案 > 谷歌字典结果抓取

问题描述

我正在尝试抓取谷歌的字典结果,但我认为我做错了。这是我要抓取的内容的屏幕截图:

1

这是我正在运行的代码:

elif 'meaning' in query:
          query = query.replace("what", "").replace("meaning", "").replace("means", "").replace("is the", "").replace("of","")
          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"
          }
          r = requests.get(f"https://www.google.com/search?q={query}", headers=headers)
          soup = BeautifulSoup(r.text, 'lxml')

          result = soup.find('div', class_= 'LTKOO sY7ric')
          print(result.span.text)
          speak(result.span.text)

我收到此错误:

Traceback (most recent call last):
  File "c:\MY Programmes\DUSTIN- THE VOICE ASSISTANT\dustin.py", line 106, in <module>
    print(result.span.text)
AttributeError: 'NoneType' object has no attribute 'span'

标签: pythonpython-3.xweb-scraping

解决方案


很可能,当您尝试时该页面尚未加载,soup.find(query)因此您可以执行time.sleep(x)或使用 wget 下载页面,并在下载后使用 soup 进行查询。

来源:BeautifulSoup 查找类返回无


推荐阅读