Python靓汤类名存在twi

2024-03-29 12:33:22 发布

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

我现在正在学习如何使用BS4,但有一件事我还没有真正弄明白,那就是如何在另一个span类中使用相同名称的span类。在

HTML示例

<span class="test class">
 <span class="another class">
  <span class="test class">
        data I want
  </span>

我对其他数据所做的是

^{pr2}$

但我想上第二堂课的时候,这要上第一堂课。提前谢谢。在


Tags: 数据test名称示例datahtmlanotherclass
3条回答
find_all('span', class_="test class")[1].get_text().strip()

这将查找class='testclass'的所有span实例,并将其存储在一个列表中。然后我们选择列表的第二个元素,它将对应于测试类的第二个存在。在

这对我有用:

from bs4 import BeautifulSoup

html = """
<span class="test class">
 <span class="another class">
  <span class="test class">
        data I want
  </span>
"""

soup = BeautifulSoup(html, 'html.parser')
span = soup.find('span', class_="test class")
print span.get_text().strip()
>>> data I want

系统详细信息:

  • Python 2.7.6
  • 美化组4==4.4.0

您需要使用another class类在元素中强制执行搜索。您可以通过链接find()调用来完成此操作:

elm = soup.find('span', class_="another class").find('span', class_="test class")
print(elm.get_text())

或者,一次性使用CSS selector

^{pr2}$

其中>表示直接的父子关系。在

相关问题 更多 >