【问题标题】:Beautiful Soup issue with webscraping [duplicate]网页抓取的美丽汤问题[重复]
【发布时间】:2016-10-09 14:55:48
【问题描述】:

我正在做一个网页抓取项目,我有以下项目我计划进行网页抓取:

<td class="country">
  <div>
    <img alt="Niger" height="27" src="http://assets.rio2016.nbcolympics.com/country-flags/52x35/NIG.png" width="40"/>
    Niger                                          
  </div>

在这种情况下,我试图将国家尼日尔排除在列表之外。我有一整张桌子,我试图把所有国家都拉出来。我当前的代码如下所示:

response = requests.get('http://www.nbcolympics.com/medals')
soup = BeautifulSoup(response.content, 'lxml')
for td in soup.findAll("td",{"class": "country"}):
   print(td)

这会让我获得很多信息。我只想关注表格中的国家/地区价值。 (此表包含所有参加奥运会的国家。)如果我尝试执行以下操作:

for td in soup.findAll("td",{"class": "country"}).children:

我收到以下错误消息:

Traceback (most recent call last):
File "idea.py", line 15, in <module>
  for row in soup.find_all('tr').children:
AttributeError: 'ResultSet' object has no attribute 'children'

我知道必须有一种方法可以查看每个 td 以提取国家/地区价值。 (我可以使用 get_text() 获取国家/地区,但它附带了更多信息。)另外,如果 div 值有一个类,那么我认为它也很容易做到。感谢您的帮助。

我也试过了:

for td in soup.findAll("img", {"width": "40"})
      print(td)

这几乎得到了我想要的。它将打印以下内容:

<img alt="Togo" height="27" src="http://assets.rio2016.nbcolympics.com/country-flags/52x35/TOG.png" width="40"/>

但是,我并没有在它之后得到这个国家!但我就在那里!

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup


    【解决方案1】:

    findAll 返回找到的元素的ResultSet,这是一个可迭代的。您需要遍历找到的元素并访问.text

    for element in soup.findAll("img", {"class": "country"}):
        print(element.get('alt', ''))
    

    我已经替换了"td",{"class": "country"} 选择器,因为您正在寻找具有country 类的图像。

    【讨论】:

    • 是的,我更新以显示当您使用 img 标签时会发生什么 - 它几乎可以让我得到我想要的,但在国家之前就停止了。所以,它只是让我得到我想要的,但不完全是!感谢您的帮助!
    • 我已经更新了我的答案,它应该可以解决你的问题。下次尝试谷歌“beautifulsoup get image alt”,你会找到答案。
    • 知道了,这似乎奏效了!谢谢!
    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 2018-10-15
    • 2019-05-05
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多