的Python - BeautifulSoup - HTML解析
问题描述:
这里的站点代码的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
打印无
请帮助我,如何解析它。
答
According to the BeautifulSoup documentation,element.string
将None
如果element
有多个孩子。
在你的情况,
print element.find('a', {'class' : 'fn openPreview'}).contents[0].string
将打印 “酒店名称”。
+0
谢谢,工作正常:) – 2011-03-23 22:59:27
也许是因为fn和openPreview是单独的类。一个元素可以有多个空间分隔的类。 – SiggyF 2011-03-23 22:43:52
奇怪的是,它看起来像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