You need to enable JavaScript to run this app. 使用Requests/Session登录Goodreads抓取数据失败,缺少什么必要配置?
优惠活动
大模型
产品
解决方案
定价
更多

使用Requests/Session登录Goodreads抓取数据失败,缺少什么必要配置?

Goodreads网页抓取登录失败修复方案
  • 你当前代码的错误点如下:
    1. 未携带浏览器User-Agent请求头,Goodreads的反爬策略会直接拦截无标识的自动化请求
    2. 表单参数n写死,该参数是登录页动态生成的校验值,硬编码固定值会导致登录校验失败
    3. 所有请求未统一携带会话上下文的校验头,容易被识别为非浏览器请求

修复后完整代码

import pprint, os, re, time
from bs4 import BeautifulSoup
import requests

if not os.path.exists("GoodReads"):
    os.makedirs("Goodreads")

user = "你的注册邮箱"
password = "你的登录密码"

# 模拟浏览器请求头,必须配置
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',
    'Referer': 'https://www.goodreads.com/user/sign_in?source=home'
}

payload = {
    'user[email]': user,
    'user[password]': password,
    'utf8':'✓'
}

with requests.Session() as sess:
    sess.headers.update(headers)
    # 请求登录页获取动态校验参数
    res = sess.get('https://www.goodreads.com/user/sign_in?source=home')
    signin = BeautifulSoup(res.content, 'html.parser')
    # 提取动态生成的authenticity_token
    payload['authenticity_token'] = signin.find('input', attrs={'name':"authenticity_token", 'type':'hidden'})['value']
    # 提取动态生成的n参数,不要硬编码
    payload['n'] = signin.find('input', attrs={'name':"n", 'type':'hidden'})['value']
    # 提交登录请求
    res = sess.post('https://www.goodreads.com/user/sign_in?source=home', data=payload, allow_redirects=True)
    # 测试分页访问
    r = sess.get('https://www.goodreads.com/shelf/show/fantasy?page=2')
    soup = BeautifulSoup(r.text, 'html.parser')
    results = soup.find_all("a", class_="bookTitle")
    # 打印第二页书籍标题,确认登录成功
    for item in results:
        print(item.get_text(strip=True))

注意事项

  • 建议两次请求间隔设置2秒以上,避免触发站点频率限制导致IP被封禁
  • 如果出现人机校验要求,可以先在浏览器手动完成登录后,将浏览器中的Cookie复制到会话中,跳过模拟登录步骤
  • 抓取数据仅可用于个人学习用途,遵守站点相关使用规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 04:27:00