使用Selenium访问myvisit.com时网页空白无法加载求助
解决Selenium访问myvisit.com页面空白问题
这类问题通常是网站通过检测Selenium的特征(如window.navigator.webdriver属性、浏览器启动参数差异)拦截自动化请求,以下是针对性解决方案:
1. 配置ChromeOptions模拟常规浏览器
添加参数让ChromeDriver行为更接近普通浏览器:
import os from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() # 禁用自动化扩展提示 options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) # 设置常规用户代理(可复制自己Chrome浏览器的UA) options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36") # 启用JavaScript(明确指定避免意外) options.add_argument("--enable-javascript") # 禁用沙箱(保留配合其他参数) options.add_argument("--no-sandbox") # 禁用GPU加速(避免部分环境渲染异常) options.add_argument("--disable-gpu") driver = webdriver.Chrome(executable_path=os.getcwd()+"\\webdriver\\chromedriver.exe", options=options)
2. 移除webdriver属性(核心步骤)
多数网站通过window.navigator.webdriver识别自动化,执行脚本移除该属性:
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})") driver.get("https://myvisit.com")
3. 用显式等待替代固定延迟
固定延迟不可靠,等待页面核心元素加载完成:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # 等待页面body元素可见,最长等待15秒 WebDriverWait(driver, 15).until(EC.visibility_of_element_located((By.TAG_NAME, "body")))
4. 确保ChromeDriver与Chrome版本匹配
ChromeDriver版本必须和本地Chrome主版本号一致,版本不兼容会导致加载异常。可在Chrome设置->关于Chrome查看版本,下载对应版本的ChromeDriver。
完整示例代码
import os from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By options = Options() options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36") options.add_argument("--enable-javascript") options.add_argument("--no-sandbox") options.add_argument("--disable-gpu") driver = webdriver.Chrome(executable_path=os.getcwd()+"\\webdriver\\chromedriver.exe", options=options) # 移除自动化识别属性 driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})") driver.get("https://myvisit.com") # 等待页面加载完成 try: WebDriverWait(driver, 15).until(EC.visibility_of_element_located((By.TAG_NAME, "body"))) print("页面加载成功") except: print("页面未加载,可尝试更换用户代理或检查网络") # 后续操作完成后关闭浏览器 # driver.quit()
内容的提问来源于stack exchange,提问作者E235
相关产品推荐
相关产品推荐

