我有以下Python代碼:美麗的湯:獲取子節點的內容
def scrapeSite(urlToCheck):
html = urllib2.urlopen(urlToCheck).read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
tdtags = soup.findAll('td', { "class" : "c" })
for t in tdtags:
print t.encode('latin1')
這將返回我下面的HTML代碼:
<td class="c">
<a href="more.asp">FOO</a>
</td>
<td class="c">
<a href="alotmore.asp">BAR</a>
</td>
我想獲得之間的文本a-節點(例如FOO或BAR),這將是t.contents.contents。不幸的是,它並不容易:) 有沒有人有一個想法如何解決?
非常感謝,任何幫助表示讚賞!
乾杯, 約瑟夫
不能這樣做,這是錯誤信息: AttributeError:'NavigableString'對象沒有屬性'內容' – 2010-10-21 13:17:39
@Joseph:我測試過了,它適用於BeautifulSoup 3.0.4,Python 2.5 .. If它可能不適合你在實際內容列表中有不同的內容。我用更通用的解決方案編輯了答案。 – 2010-10-21 13:18:26
t.find('a')。contents [0] -part訣竅:)非常感謝你 – 2010-10-21 13:26:41