2016-04-29 50 views
1

我有一個像查找xapth在beautifulsoup獲得目標標籤

<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和第一個孩子的類值類值包含HTML結構First-sv子字符串。

繼在我的代碼,做工精細

>>> "Frist-sv" in dict(soup.find("div", {"class" :"main-sv"}).findChild().attrs)["class"].split(" ") 
True 

還是喜歡在lxmlxpath任何其他方式?

我不得不使用beautifulsoup只有

回答

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