2010-09-25 25 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: 
    ....