2010-09-25 98 views
-2

我尝试使用以下示例代码以获取一个网页:Python的正则表达式切片

from urllib import urlopen 
print urlopen("http://www.php.net/manual/en/function.gettext.php").read() 

现在,我可以得到整个网页中的变量。我想获得的包含网页的东西的一部分这样

<div class="methodsynopsis dc-description"> 
    <span class="type">string</span><span class="methodname"><b>gettext</b></span> (<span class="methodparam"><span class="type">string</span> <tt class="parameter">$message</tt></span> 
    )</div> 

,这样我可以生成一个文件在其他应用程序来实现。 我想要能够提取单词“字符串”,“gettext”和“$消息”。

+2

这个问题的变化已经被问了很多次的SO。这是最权威的答案:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2010-09-25 07:53:17

回答

1

从HTML中提取信息时,不建议只将一些正则表达式拼凑在一起。 正确的这样做的方法是使用合适的HTML解析模块。 Python为此有几个好的模块 - 特别是我推荐BeautifulSoup

不要被这个名字拖延 - 这是许多人使用的一个严肃的模块,取得了巨大的成功。 documentation page有很多例子可以帮助您开始满足您的特定需求。

2

你为什么不尝试使用BeautifulSoup

示例代码:

from BeautifulSoup import BeautifulSoup 
soup = BeautifulSoup(htmldoc) 
allSpans = soup.findAll('span', class="type") 
for element in allSpans: 
    ....