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

使用Python请求lexica.art遇403错误,求获取图片提示方案

解决Lexica.art API请求403错误的方案

问题概述

尝试获取Lexica.art上关键词为"history"的图片提示时,请求返回403错误。已设置User-Agent并复制请求参数,但问题未解决,原代码如下:

import requests

url="https://lexica.art/api/trpc/prompts.infinitePrompts?batch=1&input={%220%22%3A{%22json%22%3A{%22text%22%3A%22history%22%2C%22searchMode%22%3A%22images%22%2C%22source%22%3A%22search%22%2C%22cursor%22%3A250}}}"

headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.5',
'Alt-Used': 'lexica.art',
'cache-control': 'max-age=0',
'Connection': 'keep-alive',
'Host': 'lexica.art',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'cross-site',
'TE': 'trailers',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
}

r=requests.get(url, headers=headers)
print(r.status_code)

问题原因

  1. 请求头不匹配API预期:原请求头是浏览器加载页面时的配置(比如Upgrade-Insecure-Requests、Sec-Fetch-Dest: document),但目标是API接口,这类接口通常期望接收application/json类型的响应,而非HTML文档。
  2. 跨站标识错误:Sec-Fetch-Site: cross-site会被服务器识别为跨站请求,触发反爬限制。
  3. 缺少必要验证信息:部分网站会检查会话Cookie或Referer头,验证请求来源的合法性。

修正方案

1. 调整请求头

保留API请求必需的头部,移除浏览器页面导航相关的冗余头,添加Referer标识请求来源。

2. 使用会话保持

通过requests.Session()维持会话,自动处理Cookie,提升请求合法性。

修正后的代码

import requests

# 使用会话保持
session = requests.Session()

url = "https://lexica.art/api/trpc/prompts.infinitePrompts?batch=1&input={%220%22%3A{%22json%22%3A{%22text%22%3A%22history%22%2C%22searchMode%22%3A%22images%22%2C%22source%22%3A%22search%22%2C%22cursor%22%3A250}}}"

headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.5',
    'Connection': 'keep-alive',
    'Host': 'lexica.art',
    'Referer': 'https://lexica.art/?q=history',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
}

response = session.get(url, headers=headers)
print(response.status_code)
# 若状态码正常,可打印响应内容
# print(response.json())

额外说明

如果仍返回403,可尝试以下操作:

  • 从浏览器开发者工具中复制完整的Cookie,添加到请求头的Cookie字段中。
  • 降低请求频率,避免触发反爬机制。
  • 确认参数编码正确,可尝试将input参数用json.dumps生成后再URL编码,避免手动编码出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:30:48