BeautifulSoup 只返回一个结果

BeautifulSoup only returning one result

我有一些 html 这样布置的

<div class="news-a">

 <article>
  <header>
   <h2>
     <a>destination 1</a>
   </h2>
  </header>
 </article>

 <article>
  <header>
   <h2>
     <a>destination 2</a>
   </h2>
  </header>
 </article>

 <article>
  <header>
   <h2>
     <a>destination 3</a>
   </h2>
  </header>
 </article>

</div>

我正在尝试将 BeautifulSoup 用于 return 所有目的地名称,因此我将 div 名称作为 "news-a" 的目标,因为我知道只有网站上的其中一个。我的爬虫代码是这样的:

import requests
from bs4 import BeautifulSoup

page = requests.get('url')
soup = BeautifulSoup(page.content, 'html.parser')

destinations = soup.find(class_='news-a')

for destination in destinations.find_all('h2'):
    print(destination.text)

但这只是 return 与实时 url

一起使用时 "destination 1" 的第一个结果

Sample of inspect code

一个问题是您的简化示例与您最初发布然后删除的 link 中的 HTML 截然不同。

尝试使用您的 travelindicator.com link:

import requests
from bs4 import BeautifulSoup

page = requests.get('http://www.travelindicator.com/destinations?page=1')
soup = BeautifulSoup(page.content, 'html.parser')
locs = soup.find_all(lambda tag: tag.name == 'a' 
                     and tag.get('href').startswith('locations')
                     and tag.has_attr('title')
                     and not tag.has_attr('style'))

for loc in locs:
    # `locs` is now a Python list of `a` tags, each with an href
    #     and title attribute
    if loc.get('title').startswith('Travel ideas'):
        print(loc.text)
Con Dao
Kuwait City
Funafuti
Saint Helier
Mount Kailash
Sunny Beach
Krakow
Azores
Alsace
Qaqortoq
Salt Lake City
Valkenburg
Daegu
Lviv
São Luís
Abidjan
Lampedusa
Lecce
Norfolk Island
Petra

更多关于为什么你原来的方法给你带来麻烦的原因:

在实际 link 中,当您使用

dest = soup.find('div', attrs={'class':'news-a'})

此标签只有一个 h2 属性属于您要查找的类型。您需要 find_all <h2> 标签 soup.

要查看此内容,请尝试 print(dest.prettify())。您会注意到 none 所需的城市结果包含在此嵌套结构中。请记住 find 只会找到第一个结果。如果您熟悉 HTML document tree 的概念,则其他 div ("news-a") 是兄弟姐妹,而不是此处结果的 children。

这个怎么样。更简洁的所需输出:

import requests
from bs4 import BeautifulSoup

page = requests.get('http://www.travelindicator.com/destinations?page=1').text
soup = BeautifulSoup(page,"lxml")
for item in soup.select(".news-a h2 a"):
    print(item.text)

结果:

Con Dao
Kuwait City
Funafuti
Saint Helier
Mount Kailash
Sunny Beach
Krakow
Azores
Alsace
Qaqortoq
Salt Lake City
Valkenburg
Daegu
Lviv
São Luís
Abidjan
Lampedusa
Lecce
Norfolk Island
Petra