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

如何用Python从HTML提取指定数值?使用find_all仍无法定位元素

如何从HTML报表中提取指定数值?

嘿,我看你已经搭好了基础的请求框架,但卡在了BeautifulSoup的元素定位上对吧?刚好我经常处理这类报表数据提取的问题,给你几个实用的思路和调整后的代码:

一、先搞懂目标元素的HTML特征

因为你没贴出目标页面的HTML代码,我先给你说几个报表页面常见的数值标记规律:

  • 日期(比如2018-04-01)通常会放在带class="report-date"或id="start-date"的<span>/<div>标签里
  • 统计数值(比如1,500,552、7,211)大概率在表格的<td>标签中,或者带有class="total"/data-stat="impressions"这类专属属性的元素里

二、调整你的代码,加入精准定位逻辑

我把你的代码补充了几种常见的定位方式,你可以根据实际页面的HTML结构对应修改:

from bs4 import BeautifulSoup as Soup
import requests

print('Fecha Inicio ej:2018-04-01')
start = raw_input()  # 如果你用的是Python3,记得改成input()
print('Fecha Fin ej:2018-04-01')
end = raw_input()

glob2 = []
urls = [
    'http://url.com/rtbpartners/report.php?partner=id&date_from={}&date_to={}&interval=daily'.format(start, end)
]

for url in urls:
    # 发起请求并解析页面
    response = requests.get(url)
    soup = Soup(response.text, 'html.parser')
    
    # 1. 提取日期(示例:假设日期在class为"report-date"的span标签里)
    date_tag = soup.find('span', class_='report-date')
    if date_tag:
        target_date = date_tag.get_text(strip=True)
        print(f"提取到的日期: {target_date}")
    
    # 2. 提取统计数值(示例:假设数值在class为"total-row"的表格行下的td中)
    total_row = soup.find('tr', class_='total-row')
    if total_row:
        # 取出这一行所有td的文本内容
        all_numbers = [td.get_text(strip=True) for td in total_row.find_all('td')]
        # 对应你要的三个数值,假设是第2、3、4个td(索引从0开始)
        if len(all_numbers) >= 4:
            big_total = all_numbers[1]
            num_7211 = all_numbers[2]
            num_3710 = all_numbers[3]
            print(f"提取到的数值: {big_total}, {num_7211}, {num_3710}")
            # 把结果存入glob2列表
            glob2.append([target_date, big_total, num_7211, num_3710])

三、如果还是定位不到怎么办?

你可以右键页面上的目标数值,选择「检查」查看它的HTML结构:

  • 看它的标签类型(比如是<td>还是<div>)
  • 查看它的专属属性(比如class、id、data-*)
  • 比如如果数值是在<td data-stat="total_clicks">7,211</td>里,那直接用soup.find('td', {'data-stat': 'total_clicks'})就能精准定位到它

只要根据实际的HTML结构调整定位方式,就能轻松抓取到你需要的数值啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:57:27