2013-03-19 110 views
-4

我有以下HTML:閱讀元素 -​​

<tr style='background:#DDDDDD;'> 
    <td><b>ASD</b></td> 
    <td colspan='3'>1231</td> 
</tr> 

此元素不重複的頁面上,所以它是獨一無二的。我想把單元格的內容(1231)變成一些變量。我嘗試使用HTML.parser,但它不工作

+2

你能告訴我們你試過嗎? – 2013-03-19 20:03:15

回答

0

看使用beautifulsoup這是偉大的,

from BeautifulSoup import BeautifulSoup 

soup = BeautifulSoup(html) ## feed your html page to beautifulsoup 

pleaseFind = soup.find(text="ASD") 

whatINeed = pleaseFind.findNext('td') 

print whatINeed.text 
+0

湯是這樣做的:-)謝謝 – user2188158 2013-03-19 20:21:10

+0

沒問題,你可以用它來找到錨點,段落,標題或任何你需要的東西。 – 2013-03-19 20:22:04

0

你可以使用的urllib2(你沒有安裝任何新的(至少在Windows版本的蟒蛇)):http://docs.python.org/2/howto/urllib2.html

例子:

import urllib2 
response = urllib2.urlopen('your URL') 
html = response.read() 
#html is a string containing everything on your page 

#this line (it could be a bit cleaner) finds substring "<td colspan='3'>" and 
#searches between it's position and the next "</td>" 
pos=html.find("<td colspan='3'>") 
print html[pos+len("<td colspan='3'>")+1:html.find("</td>", pos))]