Python检索给出错误响应“NoneType对象没有属性getText”

2024-10-01 04:46:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用requests库和Beauty soup库从google.com查询中检索数据。 我在扯头发。无论我尝试什么版本的代码,我都会出错

这是html代码:

<div class="LGOjhe" data-attrid="wa:/description" aria-level="3" role="heading" data-hveid="CAYQAA">
<span class="ILfuVd NA6bn">
<span class="hgKElc">
Right-click the speaker icon and select &quot;Open Sound Settings.&quot; 3. Scroll down to &quot;Input.&quot; Windows will show you which <b>microphone</b> is currently your default — in other words, which one it&#39;s using right now — and a blue bar showing your volume levels. Try talking into your <b>microphone</b>.
</span>
</span>

我使用以下代码:

        page = rq.get('http://www.google.com/search?q=where%20is%20my%20microphone',  headers = hd)
        soup = BeautifulSoup(page.content, 'html.parser')
        #answer = soup.find('span', {'class_': 'hgKElc'}).getText()
        answer = soup.find('div', {'class_': 'kJ442'}).getText()

我得到一个错误,none的响应没有getText()方法。这意味着我的检索方法失败:

File "C:\Users\User\Documents\study\PythonProjectVoice\PythonVoice03.py", line 115, in respond
    answer = soup.find('div', {'class_': 'kJ442'}).getText()
AttributeError: 'NoneType' object has no attribute 'getText'

非常感谢您的回答


Tags: 代码answerdivcomyourdatahtmlgoogle
1条回答
网友
1楼 · 发布于 2024-10-01 04:46:12

有不同的地方可以改进,但是发生错误的原因是没有像kJ442这样的类的<div>

要获取<span>的文本,请使用:

soup.find('span', {'class': 'hgKElc'}).get_text()

示例

from bs4 import BeautifulSoup

html='''
<div class="LGOjhe" data-attrid="wa:/description" aria-level="3" role="heading" data-hveid="CAYQAA">
<span class="ILfuVd NA6bn">
<span class="hgKElc">
Right-click the speaker icon and select &quot;Open Sound Settings.&quot; 3. Scroll down to &quot;Input.&quot; Windows will show you which <b>microphone</b> is currently your default — in other words, which one it&#39;s using right now — and a blue bar showing your volume levels. Try talking into your <b>microphone</b>.
</span>
</span>
'''
soup = BeautifulSoup(html,'html.parser')
soup.find('span', {'class': 'hgKElc'}).get_text()

相关问题 更多 >