Python 无法使用bs4中的选择和查找方法提取值

Python 无法使用bs4中的选择和查找方法提取值,python,beautifulsoup,Python,Beautifulsoup,在下面的代码示例中,我一直在尝试使用bs4 python从标记中提取一些信息 <div class"name"> <h1 class="fullname"> John Martin </h1> (二) 两者都有错误 AttributeError: 'NoneType' object has no attribute 'get_text' and other is [] 我做错了什么?在第一个示例中,class属性应该是fullname 在第二个示例中

在下面的代码示例中,我一直在尝试使用bs4 python从标记中提取一些信息

<div class"name">
   <h1 class="fullname"> John Martin </h1>
(二)

两者都有错误

AttributeError: 'NoneType' object has no attribute 'get_text'
and other is []

我做错了什么?

在第一个示例中,class属性应该是
fullname

在第二个示例中,CSS选择器应该是
h1.fullname
->使用
class=fullname
选择
。另外,将方法更改为
select_one()
以仅选择一个元素:

from bs4 import BeautifulSoup

txt = '''<div class"name">
   <h1 class="fullname"> John Martin </h1>'''

soup = BeautifulSoup(txt, 'html.parser')

name= soup.find('h1', class_='fullname').get_text() # <-- change to fullname
print(name)

n=soup.select_one("h1.fullname").get_text() # <-- change to h1.fullname and .select_one()
print(n)


你的意思可能是
class='fullname'
。没有带有
class='name'
h1
。投票以打字错误结束/不再可复制/以对未来访问者没有帮助的方式解决。AttributeError:“NoneType”对象没有属性“get_text”(第一个示例)@user3415869您是否正在运行我回答中所述的确切示例?因为它在这里工作。如果您使用的是Jupyter笔记本-重置/重新加载它。@user3415869您使用的是什么版本的
bs4
?我正在使用版本
4.8.1
。另外,使用我在答案中给出的确切代码(使用
html.parser
)。结果必须完全相同->两次“John Martin”。因此,全名替换为title title--size1 bio-info\u name。它们是三个类吗?错误:n=soup。选择一个('.title.title--size1.bio-info\uu name')。获取文本()属性错误:“非类型”对象没有属性“获取文本”
AttributeError: 'NoneType' object has no attribute 'get_text'
and other is []
from bs4 import BeautifulSoup

txt = '''<div class"name">
   <h1 class="fullname"> John Martin </h1>'''

soup = BeautifulSoup(txt, 'html.parser')

name= soup.find('h1', class_='fullname').get_text() # <-- change to fullname
print(name)

n=soup.select_one("h1.fullname").get_text() # <-- change to h1.fullname and .select_one()
print(n)
 John Martin 
 John Martin