首页 > 解决方案 > BeautifulSoup Python .text 方法不返回正确的文本

问题描述

我正在尝试从网站上抓取足球结果。我用 html 得到结果,当我尝试用 .text 删除它们时,我得到奇怪的输出。我使用 parent 方法来获取整个乐谱的父 HTML 元素。

刮板脚本:

        response = requests.get(url)
        html_soup = BeautifulSoup(response.text, 'html.parser')
        type(html_soup)

        results = html_soup.findAll('strong',text="East Wall Rovers")
        chosen_team_results=[]

        for result in results:
            chosen_team_results.append(result.parent.text)
        print(chosen_team_results)

HTML:

<p class="zeta"><strong>
            Killester Donnycarney FC</strong>
            1
            <strong>Cherry Orchard</strong>
            2
                        </p>
<p class="zeta"><strong>
            Ballymun United</strong>
            2
            <strong>Bluebell United</strong>
            1
                        </p>

输出:

'\r\n\t\t\tValeview Shankill\r\n\t\t\t1\r\n\t\t\tEast Wall Rovers\r\n\t\t\t5\r\n\t\t\t\t\t\t', '\r\n\t\t\tMarks Celtic FC\r\n\t\t\t0\r\n\t\t\tEast Wall Rovers\r\n\t\t\t5\r\n\t\t\t\t\t\t', '\r\n\t\t\tBlessington FC\r\n\t\t\t0\r\n\t\t\tEast Wall Rovers\r\n\t\t\t5\r\n\t\t\t\t\t\t', '\r\n\t\t\tParkvale FC\r\n\t\t\t2\r\n\t\t\tEast Wall Rovers\r\n\t\t\t1\r\n\t\t\t\t\t\t', '\r\n\t\t\tBoyne Rovers\r\n\t\t\t1\r\n\t\t\tEast Wall Rovers\r\n\t\t\t1\r\n\t\t\t\t\t\t'

我希望结果是纯文本的,只有团队和分数。

标签: pythonhtmlbeautifulsoup

解决方案


为了摆脱空白,我建议你这样做:

  for result in results:
      chosen_team_results.append(''.join(str(result.parent.text).split()))
  print(chosen_team_results)

推荐阅读