【问题标题】:Python - BeautifulSoup - HTML ParsingPython - BeautifulSoup - HTML 解析
【发布时间】:2025-12-20 00:10:12
【问题描述】:

这是网站代码的片段

<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 

打印无

请帮助我,如何解析它。

【问题讨论】:

  • 可能是因为 fn 和 openPreview 是不同的类。一个元素可以有多个空格分隔的类。
  • 奇怪的是,BeautifulSoup 似乎将 fn openPreview 视为一个类。看到这个问题:*.com/questions/1242755/…

标签: python html-parsing beautifulsoup


【解决方案1】:

According to the BeautifulSoup documentation,如果element 有多个孩子,element.string 将是 None

在你的情况下,

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

将打印“酒店名称”。

【讨论】: