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

Python用BeautifulSoup时find_all结果无法调用.text提取a标签文本怎么办

问题根因

  • find_all()返回的是匹配到的标签元素列表,列表没有.text属性,需要遍历列表中的单个标签再调用.text提取文本
  • URL拼接逻辑错误,原代码拼接后得到的是page=10、page=11,无法正确获取前两页内容
  • 打印语句放在请求判断分支外,请求失败时会出现变量未定义的报错

修正后可运行代码

import requests
from bs4 import BeautifulSoup

# 增加请求头避免被反爬拦截
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
}

for i in range(2):
    # 修正分页参数拼接
    url = f'https://www.coingecko.com/fr?page={i+1}'
    response = requests.get(url, headers=headers)
    if response.ok:
        soup = BeautifulSoup(response.text, "lxml")
        coin_tags = soup.find_all('a', class_ = 'tw-hidden lg:tw-flex font-bold tw-items-center tw-justify-between')
        # 遍历所有匹配到的标签提取文本
        for tag in coin_tags:
            print(tag.text.strip())
    else:
        print(f"第{i+1}页请求失败,状态码:{response.status_code}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:24:03