Python 爬虫实战:反爬绕过与数据解析常见问题总结
第一个坑:User-Agent 被识别为爬虫
刚开始写爬虫时,直接用 requests.get(url) 发送请求,结果返回 403 Forbidden。
问题原因:requests 默认的 User-Agent 是 python-requests/版本号,网站一眼就能识别这是爬虫。
解决方案:自定义请求头,伪装成浏览器。
import requests
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',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
}
response = requests.get(url, headers=headers, timeout=10)
print(response.status_code)
经验:Headers 越完整越像真人在访问,最少也要加上 User-Agent。
第二个坑:IP 被封禁
搞定了 User-Agent 开始爬数据,结果爬了 100 多条后,又返回 403 了。这次更惨,换浏览器也不行——IP 被封了!
问题原因:同一个 IP 短时间内请求太频繁,触发了网站的反爬机制。
解决方案:使用代理 IP 池 + 请求间隔。
import requests
import time
import random
# 代理池(示例,实际需要购买或免费获取)
proxies = [
{'http': 'http://123.45.67.89:8080', 'https': 'https://123.45.67.89:8080'},
{'http': 'http://98.76.54.32:8080', 'https': 'https://98.76.54.32:8080'},
]
def fetch_with_proxy(url):
proxy = random.choice(proxies)
headers = {: }
:
response = requests.get(url, headers=headers, proxies=proxy, timeout=)
time.sleep(random.uniform(, ))
response
Exception e:
()
page (, ):
url =
response = fetch_with_proxy(url)
response:
()

