【问题标题】:How to get text within <td> within <font> with bs4?如何使用 bs4 在 <font> 中的 <td> 中获取文本?
【发布时间】:2021-06-28 14:47:08
【问题描述】:

这应该如何使用 bs4 解析以仅获取国家/地区值?

    <tr>
        <td colspan=16>
            <font class=spy6><u>
                    <font class=spy1>Country</font> Brazil/BR<br>
                    <font class=spy1>Region </font> South America/SA <font class=spy1>TimeZone=America/Sao_Paulo
                    <font class=spy1>ORG/ASN</font> Brazil/BRORG/ASN<br></u></font>
        </td>
    </tr>

通过这段代码,我得到了 td 中的所有文本,但我不明白如何专门引用 Country

 if resp.status_code == 200:
    soup = BeautifulSoup(resp.text, 'html.parser')
    rows = soup.find_all('td')
    for row in rows:
        print(row.text)

我得到了这个字符串

 Country Brazil/BR South America/SA TimeZone=America/Sao_Paulo Location=-22.8305/-43.2192REG 
 Brazil/BRORG/ASN Locaweb Servicos de Internet S/A/27715

【问题讨论】:

  • row.find_all("font", {"class": "spy1"}) ?或 find 而不是 find_all 仅获取第一个元素 row.find("font", {"class": "spy1"})
  • 国名不在&lt;font&gt;内,只包含标签Country

标签: python parsing web-scraping beautifulsoup


【解决方案1】:

在每个 td 中找到第一个 &lt;font&gt;class='spy1'。国家在之后的文本节点中。

    rows = soup.find_all('td')
    for row in rows:
        country_label = row.find('font', _class='spy1')
        if country_label:
            print(country.next_sibling)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2017-07-27
    相关资源
    最近更新 更多