使用Python+Selenium/BS4抓取拍卖网站隐藏标签内容失败求助
解决方案
1. 绕过Selenium指纹检测
多数反爬机制会通过navigator.webdriver识别自动化工具,直接修改该属性可规避检测:
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("--headless=new") options.add_argument("--disable-blink-features=AutomationControlled") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) driver = webdriver.Chrome(options=options) # 执行脚本隐藏webdriver标识 driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
2. 模拟精细化用户行为
仅靠time.sleep()不足以模拟真实操作,结合鼠标移动、随机延迟提升真实性:
from selenium.webdriver.common.action_chains import ActionChains import random import time # 定位BIDS标签 bids_tab = driver.find_element("xpath", "//*[text()='BIDS']") # 滚动到标签居中位置 driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", bids_tab) # 随机延迟1-3秒 time.sleep(random.uniform(1,3)) # 模拟鼠标移动到标签、短暂停留后点击 ActionChains(driver).move_to_element(bids_tab).pause(random.uniform(0.5,1.5)).click().perform() # 等待内容加载 time.sleep(random.uniform(2,4))
3. 直接抓取接口数据(绕过前端交互)
打开浏览器开发者工具(F12),切换到Network标签,点击BIDS/DOCS标签观察XHR请求,直接用requests调用接口获取数据:
import requests 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://bid.hertz.ag/ui/auctions/112571/14320874", # 从浏览器复制有效Cookie字段(需包含会话验证信息) "Cookie": "your_session_cookie_here" } # 获取BIDS板块数据 bids_url = "https://bid.hertz.ag/api/auctions/112571/14320874/bids" bids_data = requests.get(bids_url, headers=headers).json() # 获取DOCS板块附件数据 docs_url = "https://bid.hertz.ag/api/auctions/112571/14320874/documents" docs_data = requests.get(docs_url, headers=headers).json()
注:Cookie可从Selenium驱动中提取:driver.get_cookies(),再转换为requests所需格式。
4. 检查并切换iframe
若目标内容嵌套在iframe中,需先切换到iframe再操作:
# 定位目标iframe iframe = driver.find_element("xpath", "//iframe[contains(@src, 'auctions')]") driver.switch_to.frame(iframe) # 定位并点击标签 bids_tab = driver.find_element("xpath", "//*[text()='BIDS']") bids_tab.click() # 操作完成后切回主文档 driver.switch_to.default_content()
5. 使用undetected-chromedriver
若上述方法无效,可尝试专门规避反爬的undetected-chromedriver库,它会自动处理多数指纹检测:
from undetected_chromedriver import Chrome, ChromeOptions options = ChromeOptions() options.add_argument("--headless=new") driver = Chrome(options=options) driver.get("https://bid.hertz.ag/ui/auctions/112571/14320874") # 直接定位并点击标签 bids_tab = driver.find_element("xpath", "//*[text()='BIDS']") bids_tab.click()
内容的提问来源于stack exchange,提问作者Phoebe Miller
相关产品推荐
相关产品推荐

