You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup4解析网页时如何打印所有匹配文本?

解决BeautifulSoup4仅输出单个解析结果的问题

你的代码有两处问题导致只能输出单个值:

  • CSS选择器语法错误,'div > div' '[class = "name"]'的写法不符合规范,正确写法应为'div > div.name'或'div > div[class="name"]'(选择器之间不能有空格)
  • 仅打印了匹配列表的第一个元素a[0].text,未遍历所有结果

修正后的代码如下:

import requests
from bs4 import BeautifulSoup as BS

response = requests.get('https://www.dotabuff.com/heroes', headers={'User-agent': 'your bot 0.1'})
html = BS(response.content, 'html.parser')

# 修正CSS选择器,匹配所有带name类的子div
hero_names = html.select('div > div.name')
# 遍历所有匹配结果,打印每个英雄名称
for name in hero_names:
    print(name.text.strip())

说明:

  • 修正后的选择器div > div.name会精准定位页面中所有英雄名称对应的元素
  • 通过for循环遍历匹配到的元素列表,逐个输出文本内容,strip()用于去除文本前后的空白字符

内容的提问来源于stack exchange,提问作者janp0l_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:50:25