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

如何不使用Selenium用Python处理Best Buy落地页的国家选择

绕过Best Buy国家选择页面的非Selenium爬取方案

问题背景

使用BeautifulSoup爬取Best Buy网站时,首次访问会遇到由JavaScript控制的国家选择页面,无法直接获取主内容。希望通过非Selenium的HTTP请求方式自动化跳过该页面。

可行解决方案

1. 直接携带地域Cookie访问

Best Buy的国家选择逻辑通常依赖Cookie标记用户的地域偏好,只需在请求中添加对应的Cookie参数,即可跳过选择页面:

  • 手动访问Best Buy网站,选择目标国家(比如美国),打开浏览器开发者工具(F12),在「Application」>「Cookies」中找到countryCode、region等关键Cookie项;
  • 将这些Cookie值添加到requests.get()的cookies参数中,模拟已完成国家选择的状态。

2. 预发送国家选择请求

如果Cookie容易过期,可以通过抓包找到国家选择的提交接口,先发送请求设置地域偏好,再用同一个会话爬取目标页面:

  • 抓包国家选择按钮的点击请求,通常是一个POST请求,包含country、language等参数;
  • 使用requests.Session()创建会话,先发送该POST请求,再用会话访问搜索页面,会话会自动保存设置好的Cookie。

3. 完善请求头地域信息

在请求头中添加地域相关字段,辅助网站自动识别地域:

  • 添加Accept-Language头,比如en-US,en;q=0.9;
  • 配合美国地区的代理IP(可选),进一步强化地域标识。

修改后的代码示例

import requests
from bs4 import BeautifulSoup

def get_random_user_agent():
    # 示例User-Agent,可扩展为随机池
    return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"

def scrape_bestbuy(product_name):
    search_url = f"https://www.bestbuy.com/site/searchpage.jsp?st={product_name.replace(' ', '+')}"
    
    # 从浏览器获取的地域Cookie(以美国为例)
    region_cookies = {
        'countryCode': 'US',
        'region': 'en-US',
        'storeId': '10501'  # 可选,指定美国门店ID
    }
    
    headers = {
        'User-Agent': get_random_user_agent(),
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
    }
    
    # 携带Cookie发送请求
    response = requests.get(search_url, headers=headers, cookies=region_cookies)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    try:
        product_title = soup.select_one('.sku-title a').text.strip()
        product_price = soup.select_one(".pricing-price div[data-testid='large-price'] .priceView-customer-price > span:nth-child(1)").text
        return {'Site': 'Bestbuy.com', 'Item title name': product_title, 'Price(USD)': product_price}
    except AttributeError:
        return {'Site': 'Bestbuy.com', 'Item title name': 'No Product Found', 'Price(USD)': 'N/A'}

注意事项

  • Cookie可能会随网站更新失效,需定期从浏览器重新获取;
  • 尽量模拟真实浏览器的完整请求头,降低被反爬识别的概率;
  • 如果网站有更严格的反爬机制,可能需要结合请求频率控制、代理IP等策略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 00:42:29