2011-03-23 113 views
1

這裏的站點代碼的Python - BeautifulSoup - HTML解析

<td class='vcard' id='results100212571'> 
<h2 class="custom_seeMore"> 
    <a class="fn openPreview" href="link.html">Hotel Name<span class="seeMore">See More...</span></a> 
</h2> 
<div class='clearer'></div> 
<div class='adr'> 
    <span class='postal-code'>00000</span> 
    <span class='locality'>City</span> 
    <span class='street-address'>Address</span> 
</div> 
<p class="tel">Phone number</p> 

片段,我嘗試分析它

for element in BeautifulSoup(page).findAll('td'): 
    if element.find('a', {'class' : 'fn openPreview'}): 
     print element.find('a', {'class' : 'fn openPreview'}).string 
    if element.find('span', {'class' : 'postal-code'}): 
     print element.find('span', {'class' : 'postal-code'}).string 
    if element.find('span', {'class' : 'locality'}): 
     print element.find('span', {'class' : 'locality'}).string 
    if element.find('span', {'class' : 'street-address'}): 
     print element.find('span', {'class' : 'street-address'}).string 
    if element.find('p', {'class' : 'tel'}): 
     print element.find('p', {'class' : 'tel'}).string 

我知道這是很業餘的代碼,但它幾乎工作。也就是說,它適用於除「FN openPreview」所有類,所有其他類吸引他們的內容,但

print element.find('a', {'class' : 'fn openPreview'}).string 

打印無

請幫助我,如何解析它。

+2

也許是因爲fn和openPreview是單獨的類。一個元素可以有多個空間分隔的類。 – SiggyF 2011-03-23 22:43:52

+0

奇怪的是,它看起來像BeautifulSoup將'fn openPreview'視爲一個類。看到這個問題:http://stackoverflow.com/questions/1242755/beautiful-soup-cannot-find-a-css-class-if-the-object-has-other-classes-too – 2011-03-23 22:48:43

回答

8

According to the BeautifulSoup documentation,element.stringNone如果element有多個孩子。

在你的情況,

print element.find('a', {'class' : 'fn openPreview'}).contents[0].string 

將打印 「酒店名稱」。

+0

謝謝,工作正常:) – 2011-03-23 22:59:27