2024-03-29 12:33:22 发布
网友
我现在正在学习如何使用BS4,但有一件事我还没有真正弄明白,那就是如何在另一个span类中使用相同名称的span类。在
HTML示例
<span class="test class"> <span class="another class"> <span class="test class"> data I want </span>
我对其他数据所做的是
但我想上第二堂课的时候,这要上第一堂课。提前谢谢。在
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
系统详细信息:
您需要使用another class类在元素中强制执行搜索。您可以通过链接find()调用来完成此操作:
another class
find()
elm = soup.find('span', class_="another class").find('span', class_="test class") print(elm.get_text())
或者,一次性使用CSS selector:
其中>表示直接的父子关系。在
>
这将查找class='testclass'的所有span实例,并将其存储在一个列表中。然后我们选择列表的第二个元素,它将对应于测试类的第二个存在。在
这对我有用:
系统详细信息:
您需要使用
another class
类在元素中强制执行搜索。您可以通过链接find()
调用来完成此操作:或者,一次性使用CSS selector:
^{pr2}$其中
>
表示直接的父子关系。在相关问题 更多 >
编程相关推荐