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

Python3.10网页爬取遇HTTP 403与308错误,请求协助解决

解决IMDB Top250爬取的403与308错误

问题根源

  • 403 Forbidden:IMDB的反爬系统识别出请求来自非浏览器客户端,直接拒绝访问,核心原因是默认请求头缺少符合标准的User-Agent标识。
  • 308 Permanent Redirect:添加简化版User-Agent后,服务器返回重定向指令,但你的请求要么没自动跟进重定向,要么请求头仍不够完整,导致无法正常访问目标页面。

有效解决方案

方法1:用urllib完善请求头+处理重定向

给请求添加更贴近真实浏览器的完整请求头,并确保开启重定向跟进:

from urllib.request import urlopen, Request
from bs4 import BeautifulSoup

url = "https://www.imdb.com/chart/top"
# 模拟Chrome浏览器的完整请求头
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',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.9'
}

request = Request(url, headers=headers)
# Python 3.9+支持follow_redirects参数,强制跟进重定向
response = urlopen(request, follow_redirects=True)
soup = BeautifulSoup(response, 'html.parser')

# 测试:提取第一部电影标题
first_title = soup.find('td', class_='titleColumn').a.get_text()
print(first_title)

方法2:改用requests库(更省心)

requests默认自动处理重定向,请求头设置更简洁,适合快速解决问题:

import requests
from bs4 import BeautifulSoup

url = "https://www.imdb.com/chart/top"
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'
}

# 发送GET请求,自动处理重定向
response = requests.get(url, headers=headers)
# 主动抛出请求错误,方便排查问题
response.raise_for_status()

soup = BeautifulSoup(response.text, 'html.parser')
first_title = soup.find('td', class_='titleColumn').a.get_text()
print(first_title)

注意事项

  • 不要只用Mozilla/5.0这种极简User-Agent,这类标识很容易被反爬系统识别为爬虫,尽量用真实浏览器的完整User-Agent(可在浏览器开发者工具中查看)。
  • 爬取IMDB前请务必阅读其Robots协议,确保你的爬取行为符合网站规则,避免触发更严格的反爬限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:35:17