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

如何使用BeautifulSoup4、Python3及requests库提取网页href链接

代码问题修复与实现方案

现有代码问题

  • 正则匹配时传入的page是requests返回的Response对象,不是HTML文本,运行会直接报错
  • BeautifulSoup3已停止维护,不需要使用,BeautifulSoup4完全可以满足当前提取需求,比正则匹配更稳定,不需要手动处理标签格式容错
  • 缺少User-Agent请求头,目标站点可能会拦截无标识的爬虫请求
  • 未处理相对路径的href链接,提取到的链接无法直接用于下载

完整实现代码

第一步:提取所有shape文件下载链接

import requests
from bs4 import BeautifulSoup

URL = 'https://earth-info.nga.mil/index.php?dir=coordsys&action=gars-20x20-dloads'
# 加请求头模拟浏览器访问,避免被反爬拦截
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}

response = requests.get(URL, headers=headers)
# 自动适配页面编码避免乱码
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.text, 'html.parser')

shape_download_links = []
# 遍历所有带href属性的a标签
for a_tag in soup.find_all('a', href=True):
    href_val = a_tag['href']
    # 筛选shape文件相关链接,通常shape文件会打包为zip分发,可根据实际站点的文件后缀调整规则
    if href_val.endswith('.zip') or href_val.endswith('.shp'):
        # 补全相对路径的域名
        if not href_val.startswith('http'):
            href_val = 'https://earth-info.nga.mil/' + href_val.lstrip('/')
        shape_download_links.append(href_val)

# 打印所有提取到的下载链接
for link in shape_download_links:
    print(link)

第二步:批量自动下载文件(可选)

如果需要直接下载所有文件,追加以下代码即可:

import os

# 本地保存目录,不存在会自动创建
save_folder = './gars_shape_files'
os.makedirs(save_folder, exist_ok=True)

for download_url in shape_download_links:
    file_name = download_url.split('/')[-1]
    save_path = os.path.join(save_folder, file_name)
    # 流式下载适配大文件,避免内存溢出
    file_resp = requests.get(download_url, headers=headers, stream=True)
    with open(save_path, 'wb') as f:
        for chunk in file_resp.iter_content(chunk_size=1024 * 1024):
            if chunk:
                f.write(chunk)
    print(f"{file_name} 下载完成")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:15:08