【问题标题】:BeautifulSoup finding nested tags, childrenBeautifulSoup 查找嵌套标签,儿童
【发布时间】:2018-06-24 23:40:54
【问题描述】:

我看到一堆关于查找标签和标签内信息的信息,但我似乎找不到同样简单的东西。我要做的是访问第三个“td”元素中“a”元素(在本例中为“United States”)的文本或标题。我遇到的问题是第三个“td”元素的“样式”与第一个“td”元素(“text-align:left”)相同,所以我不能用它过滤,nextSibling只让我下一层,到第二个“td”元素。我的其余代码有效(尽管它使我使用了我认为过时的 BeautifulSoup 语法,即使我安装了 Python 3.6.5 和 BS 4.6。我猜这是另一个问题)。我正在尝试使“国家”变量起作用,并且尝试了多种方法,但是除了在末尾放置一堆 .next.next.next 之外,我没有尝试过任何方法。

HTML(https://en.wikipedia.org/wiki/Toronto_FC#Current_roster):

<td style="text-align: left">
  <a href="/wiki/Goalkeeper_(association_football)"
  title="Goalkeeper (association football)">Goalkeeper</a>
</td>
<td style="padding-right:15px;">
    <span class="fn">...</span>
</td>
<td style="text-align: left">
    <span class="flagicon">...</span>
    <a href="/wiki/United_States" title="United States">United States</a> 
</td>

我的代码:

vcard = page_soup.findAll("tr", {"class": "vcard agent"})
cards = vcard[0]

for cards in vcard:
    league = page_soup.find("a", {"title": "Major League Soccer"})
    league_name = league.text

    team = page_soup.find("h1", {"class": "firstHeading"})
    team_name = team.text

    position = cards.a.text

    name = cards.findAll("span", {"class": "fn"})
    player_name = unidecode(name[0].text)

    ***this variable not working***
    country = cards.find("td", {"style": "text-align: left")

【问题讨论】:

    标签: python beautifulsoup findall nextsibling


    【解决方案1】:

    如果有疑问,请使用 css 选择器。毫无疑问时使用 css 选择器

    但很明显,它只有在您确定它永远是第三个td时才有效

    country = cards.select_one('td:nth-of-type(3) a')
    print(country['title'], country.text)
    

    【讨论】:

    • 此代码将整个元素作为列表返回,因此它不适用于我获取文本的目的。
    • 亲爱的,谢谢!我实际上将其调整为:country = cards.select_one('td:nth-of-type(3) a').text 并且效果很好