2011-08-16 23 views
-1

可能重复:
Parsing HTML in Python如何解析一个html文件并通过使用Python获取标签之间的文本?

我寻觅更多在互联网上得到这是通过使用Python标签之间的文本。你们能解释一下吗?

+1

严,http://docs.python.org/library/htmlparser.html? –

+0

或http://www.crummy.com/software/BeautifulSoup/documentation.html或http://lxml.de/ – agf

+0

或http://stackoverflow.com/questions/6870446/whats-the-most-forgiving- html-parser-in-python或http://stackoverflow.com/questions/5120129/python-html-parsing或http://stackoverflow.com/questions/4895102/python-html-parsing或http:// stackoverflow。 com/questions/2505041/best-library-to-parse-html-with-python-3-and-example – agf

回答

-1

上面评论中链接中提供的htmlparser可能是更强大的方法。但是,如果你有这是特定标记之间内容的简单一点,你可以使用regular expressions

import re 
html = '<html><body><div id='blah-content'>Blah</div><div id='content-i-want'>good stuff</div></body></html>' 
m = re.match(r'.*<div.*id=\'content-i-want\'.*>(.*?)</div>', html) 
if m: 
    print m.group(1) # Should print 'good stuff' 
+0

我不同意使用正则表达式来解析HTML。你的代码只能用最简单的例子。如果div有任何其他属性(如类),它会失败。如果div中的文本带有'>',则会失败。对于除了一个不现实的简单例子之外的任何东西,正则表达式都是不够的。另请参阅http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – murgatroid99

+0

是的HTML解析器库是要走的路。但是可能会出现这样的情况:您正在从固定的HTML格式中读取数据,或者您没有任何内容,但内置了python库。在这种情况下,上面的代码,我已经纠正应该工作。是的,它不如HTML解析器那样健壮,因此是我答案的第一行。 – arunkumar

2

下面是一个使用BeautifulSoup解析HTML的例子:

from BeautifulSoup import BeautifulSoup 
soup = BeautifulSoup("""<html><body> 
         <div id="a" class="c1"> 
          We want to get this 
         </div> 
         <div id="b"> 
          We don't want to get this 
         </div></body></html>""") 
print soup('div', id='a').text 

此输出

We want to get this 
相关问题