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

使用BeautifulSoup提取Cotswold Fayre商品价格遇302跳转问题求助

问题描述

尝试从需要身份验证的网站https://www.cotswold-fayre.co.uk/提取商品价格,编写的Python代码通过requests.Session传入用户名密码登录返回200状态码,但获取商品页面时仍显示“Product Price: Login To Buy”。同时发现登录后Web UI返回302状态码,求解决方法。

代码如下:

import requests
from bs4 import BeautifulSoup
import pandas as pd


username = 'testuser@gmail.com'
password = 'test@123'


num_pages = 10

# Create a session
session = requests.Session()


login_url = 'https://www.cotswold-fayre.co.uk/login'
login_data = {
    'email': username,
    'password': password
}
session.post(login_url, data=login_data)

# Initialize lists to store the extracted information
links = []
titles = []
model_numbers = []
barcodes = []
prices = []

# Iterate over each page
for page in range(1, num_pages + 1):
    # Send a GET request to the website for each page
    url = f'https://www.cotswold-fayre.co.uk/products/?page={page}'
    response = session.get(url)

    # Create a BeautifulSoup object to parse the HTML content
    soup = BeautifulSoup(response.content, 'html.parser')
    # Find all the product elements on the page
    product_elements = soup.find_all('div', class_='product-item-info')
    print(product_elements)
解决思路与步骤

1. 处理登录表单的隐藏验证字段

直接POST用户名密码大概率失败,因为多数网站的登录表单包含CSRF令牌或其他隐藏字段,需要先获取登录页面提取这些字段再提交:

# 先请求登录页面,提取表单内的所有隐藏字段
login_page = session.get(login_url)
soup_login = BeautifulSoup(login_page.content, 'html.parser')
form = soup_login.find('form')

# 把表单里的所有input字段加入登录数据
for input_tag in form.find_all('input'):
    name = input_tag.get('name')
    value = input_tag.get('value')
    if name:
        login_data[name] = value

# 提交登录请求,注意使用表单的action地址(如果存在)
login_response = session.post(form.get('action') or login_url, data=login_data)

2. 确认登录状态与重定向处理

  • 不要只看200状态码,检查login_response.text是否包含登录成功标识(比如“Logout”按钮、用户名)
  • requests.Session默认自动处理302重定向,若手动关闭过需开启allow_redirects=True
  • 打印login_response.url确认是否跳转到了登录后的页面

3. 添加浏览器请求头伪装

网站会通过请求头识别非浏览器请求,给session添加常见请求头:

session.headers.update({
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Referer': login_url
})

4. 检查会话Cookie一致性

登录后打印session.cookies,对比浏览器登录后的Cookie列表,确保关键认证Cookie(如customer、PHPSESSID)已被session保存。

5. 调试商品页面响应

获取商品页面后,打印响应内容的前几百字符,确认是否真的处于登录状态:

print(response.text[:500])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:05:10