在beautifulsoup中找到xapth以获取目标标记

时间:2016-04-29 16:04:18

标签: python beautifulsoup

我有像

这样的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

1 个答案:

答案 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