【问题标题】:How to extract href content using beautifulsoup in python如何在python中使用beautifulsoup提取href内容
【发布时间】:2020-09-11 09:32:59
【问题描述】:
import requests
from bs4 import BeautifulSoup

page = requests.get('http://espn.go.com/nba/team/roster/_/name/atl/atlanta-hawks')
soup = BeautifulSoup(page.content, "html.parser")
player_list = soup.find_all(class_="Image__Wrapper")
#player_list = soup.find_all("tr")
print(player_list[1])

我得到的输出是

<div class="Image__Wrapper aspect-ratio--child"><img alt="https://a.espncdn.com/i/headshots/nba/players/full/3062667.png" class="" data-mptype="image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" title="DeAndre' Bembry"/></div>

我只对 DeAndre' Bembry 感兴趣,我该如何提取它。我也有点困惑如何获取所有玩家姓名的列表。

【问题讨论】:

  • 输出在哪里?
  • Andrej 更新了输出,你现在看到了

标签: python list beautifulsoup href


【解决方案1】:

你可以试试

import requests
from bs4 import BeautifulSoup

page = requests.get('http://espn.go.com/nba/team/roster/_/name/atl/atlanta-hawks')
soup = BeautifulSoup(page.content, "html.parser")
player_list = soup.find_all(class_="Image__Wrapper")
#player_list = soup.find_all("tr")
print(player_list[1].img["title"])

输出

 DeAndre' Bembry

并打印所有玩家

print([i.img["title"] for i in player_list if 0 < i.img["title"].count(" ") <= 3])

输出

["DeAndre' Bembry", 'Charlie Brown Jr.', 'Clint Capela', 'Vince Carter', 'John Collins', 'Dewayne Dedmon', 'Bruno Fernando', 'Brandon Goodwin', 'Treveon Graham', 'Kevin Huerter', "De'Andre Hunter", 'Damian Jones', 'Skal Labissiere', 'Cam Reddish', 'Jeff Teague', 'Trae Young']

【讨论】:

  • 谢谢,我该如何获取所有的名字列表?无需手动打印每个索引?
  • print([i.img["title"] for i in player_list])
  • 最后一个问题,你为什么要放 if 0
  • 这是为了删除一些不是玩家名字的句子。
【解决方案2】:
player_list[1].find_next('img').get('title')  # "DeAndre' Bembry"

【讨论】:

  • 谢谢,我该如何获取所有的名字列表?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-16
相关资源
最近更新 更多