使用Python Selenium访问Lowes页面为何出现404错误及解决方法
解决Lowes页面Selenium访问404问题
手动浏览器可正常访问但Selenium返回404,核心原因是网站反爬机制识别了自动化会话,以下是针对性解决方法:
1. 强化浏览器指纹伪装
undetected_chromedriver的基础伪装可能不足以绕过检测,补充参数模拟真实浏览器环境:
import undetected_chromedriver as uc from selenium.webdriver.chrome.options import Options import time options = Options() # 替换为你手动浏览器的用户代理(可通过浏览器内置工具获取) options.add_argument("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") # 设置真实窗口尺寸 options.add_argument("window-size=1920,1080") # 禁用自动化特征检测 options.add_argument("--disable-blink-features=AutomationControlled") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) driver = uc.Chrome(options=options) # 隐藏navigator.webdriver属性 driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})") website = 'https://www.lowes.com/pl/Drywall-joint-compound-Drywall-Building-supplies/4294858286?refinement=1' driver.get(website) time.sleep(5) # 给页面足够加载时间 for _ in range(4): driver.execute_script("window.scrollBy(0, 2000);") time.sleep(2)
2. 导入手动浏览器的Cookie
手动访问时的Cookie可证明“真实用户”身份,导入后绕过部分拦截:
- 手动打开Chrome访问Lowes,按F12进入开发者工具 → Application → Cookies,复制所有Cookie的
name和value。 - 在代码中添加Cookie(需先访问首页避免跨域):
# 先打开Lowes首页 driver.get("https://www.lowes.com/") # 替换为你复制的Cookie列表 cookies = [ {"name": "LOWES_SESSION", "value": "your_session_value"}, {"name": "LOWES_ID", "value": "your_id_value"} # 补充所有复制的Cookie项 ] for cookie in cookies: driver.add_cookie(cookie) # 再访问目标页面 driver.get(website)
3. 优化交互行为
避免机械性快速操作,改用贴近真人的交互方式:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import random # 等待页面核心元素加载完成(替换为页面实际存在的元素选择器) WebDriverWait(driver, 15).until( EC.presence_of_element_located(("css selector", ".product-list")) ) # 模拟自然滚动,每次滚动小段距离+随机延迟 for _ in range(12): driver.execute_script("window.scrollBy(0, 250);") time.sleep(random.uniform(0.3, 0.8))
4. 检查IP状态
如果你的IP已被Lowes封禁,需使用代理IP:
# 添加代理参数(替换为有效代理地址) options.add_argument("--proxy-server=http://123.45.67.89:8080")
内容的提问来源于stack exchange,提问作者ryan houghton
相关产品推荐
相关产品推荐

