[英]Python Beautiful soup retrieval gives an error response 'NoneType object has no attribute getText
Im trying to retrieve data from a google.com query using requests library and beautiful soup library.我正在尝试使用请求库和漂亮的汤库从 google.com 查询中检索数据。 Im tearing my hair out.
我把头发扯掉了。 Whatever version of code I try I get an error.
无论我尝试什么版本的代码,我都会收到错误消息。
This is the html code:这是 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 "Open Sound Settings." 3. Scroll down to "Input." Windows will show you which <b>microphone</b> is currently your default — in other words, which one it's using right now — and a blue bar showing your volume levels. Try talking into your <b>microphone</b>.
</span>
</span>
I use the following code:我使用以下代码:
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()
I get an error that the response of none does not have a getText()
method.我收到一个错误,即 none 的响应没有
getText()
方法。 which means my retrieval method has failed:这意味着我的检索方法失败了:
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'
Any answers much appreciated.任何答案都非常感谢。
There are different things, that could be improved, but the error occurred cause there is no <div>
with a class like kJ442
有不同的东西,可以改进,但发生错误的原因是没有
<div>
和像 kJ442 这样的kJ442
To get the text of the <span>
use:要获取
<span>
的文本,请使用:
soup.find('span', {'class': 'hgKElc'}).get_text()
Example例子
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 "Open Sound Settings." 3. Scroll down to "Input." Windows will show you which <b>microphone</b> is currently your default — in other words, which one it'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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.