2016-07-25 88 views
1

我遇到一个问题,它可能很容易,但我没有在文档中看到它。Python BeautifulSoup只选择顶部标签

这里是目标html结构,非常简单。

<h3>Top 
    <em>Mid</em> 
    <span>Down</span> 
</h3> 

我想这是h3标签内的“顶”的文字,我写这个

from bs4 import BeautifulSoup 
html ="<h3>Top <em>Mid </em><span>Down</span></h3>" 
soup = BeautifulSoup(html) 
print soup.select("h3")[0].text 

但它会返回Top Mid Down,我怎么修改呢?

回答

1

得到每个标签内的数据,你可以使用找到设置文本= True and recursive = False

In [2]: from bs4 import BeautifulSoup 
    ...: html ="<h3>Top <em>Mid </em><span>Down</span></h3>" 
    ...: soup = BeautifulSoup(html,"html.parser") 
    ...: print(soup.find("h3").find(text=True,recursive=False)) 
    ...: 
Top 

根据格式,有很多不同的方式:

print(soup.find("h3").contents[0]) 
print(next(soup.find("h3").children)) 
print(soup.find("h3").next) 
+0

谢谢,我会检查更多关于'contents'和'children'的细节 –

0

尝试这样:

from bs4 import BeautifulSoup 
html ="<h3>Top <em>Mid </em><span>Down</span></h3>" 
soup = BeautifulSoup(html) 
print soup.select("h3").findChildren()[0] 

虽然我不能完全肯定。检查此 - How to find children of nodes using Beautiful Soup

基本上你需要狩猎第一childNode

+0

。在你的代码的语法错误,但感谢您的信息。 –

-1

它容易让你使用正则表达式 像这样

pageid=re.search('<h3>(.*?)</h3>', curPage, re.DOTALL) 

搜索和使用pageid.group(value)方法

+0

谢谢,但我认为在BeautifulSoup中获得内容会更容易。 –