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

使用Python requests模块从网页下拉列表采集数据表

爬取Bakken油井页面下拉菜单中的所有数据表

要从指定页面爬取下拉菜单对应的所有数据表,基于你已有的初始代码,可按以下步骤完成:

步骤1:解析下拉菜单的所有选项

首先从初始页面中提取下拉菜单里的所有选项,每个选项对应一个需要抓取的数据表:

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/91.0.4472.124 Safari/537.36'
}

base_url = 'https://www.dmr.nd.gov/oilgas/bakkenwells.asp'
page = requests.get(base_url, headers=headers)
soup = BeautifulSoup(page.text, 'html.parser')

# 定位下拉菜单并提取选项(已确认页面select的name属性为selReport)
select_element = soup.find('select', {'name': 'selReport'})
menu_options = []
for option in select_element.find_all('option'):
    option_value = option.get('value')
    if option_value and option_value != '':  # 跳过空值选项
        menu_options.append({
            'title': option.text.strip(),
            'value': option_value
        })

步骤2:逐个请求并解析对应的数据表

该页面通过POST表单提交下拉选项值返回对应数据表,针对每个选项构造POST请求,提取并处理表格数据:

for option in menu_options:
    # 构造表单提交数据
    form_data = {'selReport': option['value']}
    # 发送POST请求获取对应页面
    response = requests.post(base_url, data=form_data, headers=headers)
    table_soup = BeautifulSoup(response.text, 'html.parser')
    
    # 定位页面中的数据表(已确认表格class为data)
    target_table = table_soup.find('table', {'class': 'data'})
    if not target_table:
        print(f"{option['title']} 未找到对应数据表")
        continue
    
    # 提取表头和行数据
    headers = [th.text.strip() for th in target_table.find_all('th')]
    rows = []
    for row in target_table.find_all('tr')[1:]:  # 跳过表头行
        row_data = [td.text.strip() for td in row.find_all('td')]
        rows.append(row_data)
    
    # 输出数据示例
    print(f"\n=== {option['title']} ===")
    print("表头:", headers)
    print("前3行数据:", rows[:3])
    
    # 可选:将数据保存为CSV文件
    # import csv
    # with open(f"{option['title'].replace('/', '_')}.csv", 'w', newline='', encoding='utf-8') as f:
    #     writer = csv.writer(f)
    #     writer.writerow(headers)
    #     writer.writerows(rows)

关键说明

  • 参数与元素定位:页面下拉菜单的name属性为selReport,数据表的class为data,均从页面源码中确认,确保请求和解析的准确性。
  • 请求头设置:添加User-Agent模拟浏览器请求,避免被服务器拦截。
  • 数据扩展:可根据需求将提取的表格数据保存为Excel、存入数据库或进行进一步分析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 23:47:41