Python-Beautiful Soup-类名存在两次
我现在正在学习如何使用BS4,但有一件事我还没有真正弄明白,那就是如何在另一个同名的span类中获取一个span类 HTML示例Python-Beautiful Soup-类名存在两次,python,beautifulsoup,Python,Beautifulsoup,我现在正在学习如何使用BS4,但有一件事我还没有真正弄明白,那就是如何在另一个同名的span类中获取一个span类 HTML示例 <span class="test class"> <span class="another class"> <span class="test class"> data I want </span> 但是我想上第二节课的时候,这是第一节课。提前谢谢 find_all('span', clas
<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
从bs4导入美化组
html=”“”
我想要的数据
"""
soup=BeautifulSoup(html,'html.parser')
span=soup.find('span',class=“测试类”)
打印span.get_text().strip()
>>>我想要的数据
系统详细信息:
- Python 2.7.6
- beautifulsoup4==4.4.0
find()
调用来实现:
elm = soup.find('span', class_="another class").find('span', class_="test class")
print(elm.get_text())
或者,一次性使用:
其中,
表示直接的父子关系。您能解释更多吗?但是如果html=“”我不想要数据”“我想要的数据”“
elm = soup.find('span', class_="another class").find('span', class_="test class")
print(elm.get_text())
elm = soup.select_one("span.another.class > span.test.class")
print(elm.get_text())