python - 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'
我希望结果是纯文本的,只有团队和分数。
解决方案
为了摆脱空白,我建议你这样做:
for result in results:
chosen_team_results.append(''.join(str(result.parent.text).split()))
print(chosen_team_results)
推荐阅读
- nest - Elasticclient - 两分钟后响应时间延长
- java - 使用 Swing 调整图标大小并在按钮上显示它们
- flutter - Flutter BottomNavigationBar 带 Navigator 且无需替换(丢失状态)
- python - 为什么列表列表中的某些元素会转换为浮点数据类型,而有些则不会?
- redhat - 如何在引导决策表中添加条件状态的对象列表?
- java - 是否有支持 Java 14 的 tomee-maven-plugin 版本?
- javascript - 减少用于添加类的多个 if 语句(jQuery)
- csv - 将 CSV 附件导入 Power Automate 时出现问题
- php - 从 PHP PDO 中的 pgSQL INSERT..ON CONFLICT RETURNING 获取值
- java - 使用 java api t24 的输入例程