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

如何使用Python提取HTML数据?解决403错误并导出为CSV文件

Python提取HTML数据导出CSV的403问题解决及完整实现

报错原因

HTTP 403 Forbidden错误是因为目标网站开启了反爬校验,会识别请求头的User-Agent字段,urllib默认发送的请求UA会被标记为爬虫,因此直接拒绝访问。

修复访问问题的两种实现

方案1:原生urllib添加请求头

from urllib.request import Request, urlopen

url = 'http://book.ponniyinselvan.in/part-1/chapter-1.html'
# 构造请求头,模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
req = Request(url=url, headers=headers)
page = urlopen(req)
# 读取HTML内容
html_content = page.read().decode('utf-8')

方案2:使用requests库(更简便,推荐)

首先安装依赖:
pip install requests
请求代码:

import requests

url = 'http://book.ponniyinselvan.in/part-1/chapter-1.html'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
resp = requests.get(url, headers=headers)
resp.encoding = 'utf-8'
html_content = resp.text

完整实现:HTML解析+CSV导出

需要先安装解析库:
pip install beautifulsoup4 lxml
以下示例实现提取章节内容、存储为CSV,可根据实际页面结构调整提取规则:

import csv
import requests
from bs4 import BeautifulSoup

url = 'http://book.ponniyinselvan.in/part-1/chapter-1.html'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
# 1. 获取HTML内容
resp = requests.get(url, headers=headers)
resp.encoding = 'utf-8'
# 2. 解析HTML
soup = BeautifulSoup(resp.text, 'lxml')
# 示例提取规则,可按需修改
chapter_title = soup.find('h1').text.strip()
paragraphs = [p.text.strip() for p in soup.find_all('p')]
# 3. 导出为CSV
with open('chapter_content.csv', 'w', encoding='utf-8-sig', newline='') as f:
    writer = csv.writer(f)
    # 写入表头
    writer.writerow(['章节名称', '段落内容'])
    # 写入数据
    for para in paragraphs:
        if para: # 过滤空段落
            writer.writerow([chapter_title, para])

注:utf-8-sig编码可避免Windows系统下打开CSV出现乱码问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 04:54:09