【问题标题】:BeautifulSoup4 - Getting incorrect text output with `getText()`BeautifulSoup4 - 使用 `getText()` 得到不正确的文本输出
【发布时间】:2019-09-05 17:04:03
【问题描述】:

我正在尝试从名为 Elite Prospects (https://www.eliteprospects.com/team/41/jokerit) 的网站上提取一些文本。这是页面的源代码:

<div class="semi-logo">
    Jokerit
            <small>
            <span>
                <i> <img class="nation-flag" src="//files.eliteprospects.com/layout/flagsmedium/9.png"> </i>
                <a href="https://www.eliteprospects.com/league/khl">KHL</a>
            </span>
        </small>
    </div>            

我特别想提取球队名称(在本例中为“Jokerit”),以及位于 a href 标记中的联赛名称。我成功地提取了联赛名称,但是我尝试提取团队名称的方式给了我“JokeritKHL”。我将此代码用于多个示例,因此它还需要能够提取两个单词的团队名称(例如“Guelph Storm”)。

这是我的代码:

team_logo= scraper.find(class_='semi-logo')
team_name = team_logo.getText(strip=True)
league = team_logo.find('a')
league = league.getText()
print(league)
print(team_name)

这是我得到的当前输出:

KHL
JokeritKHL

有什么想法吗?

我想知道有没有办法只获得“Jokerit”部分

【问题讨论】:

标签: python beautifulsoup html-parsing


【解决方案1】:

您可以为此使用.find(),如下所示:

from bs4 import BeautifulSoup

my_html = """
<div class="semi-logo">
    Jokerit
            <small>
            <span>
                <i> <img class="nation-flag" src="//files.eliteprospects.com/layout/flagsmedium/9.png"> </i>
                <a href="https://www.eliteprospects.com/league/khl">KHL</a>
            </span>
        </small>
    </div>  
"""

soup = BeautifulSoup(my_html, 'lxml')

extracted_text = soup.div.find(text=True)
print(extracted_text.strip())

如果您查看soup.div.children,您会看到标签中有三个直接后代元素:标签之前的文本、标签(及其内容),最后是更多的文本,因为在这种情况下最后有一个\n。所以这只是返回文本元素。 .strip 去掉了多余的空格。

【讨论】:

    【解决方案2】:

    team_name = team_logo.getText(strip=True)。 这将返回类 semi-logo 层次结构下的 all 文本。 因此你得到Jokerit + KHL

    【讨论】:

    • 嗨@Dave123 感谢您的新回复。我理解“team_name = team_logo.getText(strip=True)。这将返回类半徽标层次结构下的所有文本。因此你得到的是 Jokerit + KHL。”我想知道的是有没有办法只得到“Jokerit”部分
    【解决方案3】:

    它们也可以通过字符串的正则表达式轻松抓取

    import requests, re
    
    urls = ['https://www.eliteprospects.com/team/552/guelph-storm','https://www.eliteprospects.com/team/41/jokerit']
    p = re.compile(r"sv2: '(.*)'")
    with requests.Session() as s:
        for url in urls:
            r = s.get(url)
            print(p.findall(r.text)[0])
    

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 2017-01-03
      • 2011-10-20
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多