我读了一大堆文章,找不到任何真正相关的东西。我保证:)这是在Python2.7.3下的BS4和lxml解析器中实现的。
我有这样的经历:
self.chaptername = self.soup.find_all('center h3 b')在我的html中我有
<center><h3><b>Chapter 34</b></h3></center>我期望得到“第34章”的结果,但得到的结果集为空。
如果我查找'b‘,我会得到所有粗体文本的结果集(带有属性)。
如果我查找'h3 b‘,我得到一个空的结果集。
我是否应该能够查找<center><h3><b>嵌套结构,或者我使用BS4是错误的?
谢谢你,艾德
发布于 2021-08-13 13:29:02
您正在调用BeautifulSoup的.find_all()函数。这需要一个name argument,它可以是字符串、正则表达式、列表、函数或值True。
对于字符串,这应该是单个标记的名称,在本例中,您可以使用center来定位<center>标记。使用name="center h3 b"将无法定位<b>标记内的文本。如果您希望按顺序返回多种类型的标签,例如all <h1>和all <h2>,则可以使用列表。
注意,如果您只请求<center>标记的文本,它将正确地显示其中的所有文本,因此将为您提供Chapter 34,而无需定位<b>标记。
如果你只想匹配<b>标签中的<h3>标签和<center>标签中的<center>标签,那么考虑下面的例子,让事情变得更清晰一些:
from bs4 import BeautifulSoup
html = "<center><h3><b>Chapter 34</b></h3></center>"
soup = BeautifulSoup(html, 'lxml')
for center in soup.find_all('center'):
print("center soup:", center) # all html soup
print("center text:", center.text) # all text
h3 = center.find('h3')
if h3:
b = h3.find('b')
if b:
print("b text v1:", b.text)
# Alternative methods
print("b text v2:", center.find('h3').find('b').text)
print("b text v3:", center.h3.b.text)这将显示:
center soup: <center><h3><b>Chapter 34</b></h3></center>
center text: Chapter 34
b text v1: Chapter 34
b text v2: Chapter 34
b text v3: Chapter 34在这里,center用于定位<h3>标记,如果存在,则用于定位<b>标记,如果存在,则显示文本。
在每个点上,如果标记不存在,.find()调用都会返回None,因此应该小心处理这个问题(这取决于要解析的HTML )。
BeautifulSoup为创建一个简单的.find()提供了一种简写方式,center.h3.b将是等效的。
如果存在不总是具有正确结构的情况,则可以将最后两个示例包装在try / except子句中。
https://stackoverflow.com/questions/68612203
复制相似问题