我有像
这样的Html结构<html>
<body>
<-- Some tags -->
<div class="main-sv">
<div class="first-sv custom-sv">
<-- Some tags and content-->
</div>
</div>
</body>
</html>
我想查看div
的第一个子类的类值是哪个类值为main-sv
而子标记是div,类值是否包含First-sv
子字符串。
在我的代码中可以正常使用
>>> "Frist-sv" in dict(soup.find("div", {"class" :"main-sv"}).findChild().attrs)["class"].split(" ")
True
还有xpath
中的lxml
吗?
我必须只使用 beautifulsoup
答案 0 :(得分:0)
不,如上所述here BeautifulSoup本身不支持xpath查找。但这是一个稍微简化的解决方案:
from bs4 import BeautifulSoup
html = """
<div class="main-sv">
<div class="first-sv custom-sv">
<-- Some tags and content-->
</div>
</div>
"""
soup = BeautifulSoup(html, 'html.parser')
print 'first-sv' in soup.find('div', {'class':'main-sv'}).find('div')['class']
# prints True
或另一个,使用选择
parent = soup.find('div', {'class':'main-sv'})
child = parent.select('div')[0]
print 'first-sv' in child['class']
# prints True