Selenium无法在同一页面依次访问多URL问题求助
问题解决方法
你的问题出在使用了--remote-debugging-port=9222参数,这个参数用于开启Chrome的远程调试模式,允许外部连接已运行的Chrome实例,但会干扰Selenium对当前页面的正常控制,导致后续driver.get()调用无法在当前标签页跳转,反而打开新标签页。
具体修复步骤:
- 移除远程调试端口参数:删掉
options.add_argument('--remote-debugging-port=9222'),该参数并非启动新浏览器实例进行自动化控制的必需项。 - 版本兼容性检查:确保ChromeDriver版本与便携版Chrome的版本完全匹配,版本不兼容会引发各类异常行为。
- 代码结构优化(可选):将多个独立函数替换为循环遍历URL列表,让代码更简洁易维护。
修改后的完整代码:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import time chrome_driver_path = 'E:/chromedriver.exe' portable_chrome_path = 'E:/chromeX1/GoogleChromePortable.exe' user_data_dir = 'E:/chromeX1/data' options = Options() options.add_argument(f'user-data-dir={user_data_dir}') options.add_argument('--profile-directory=Default') options.binary_location = portable_chrome_path driver = webdriver.Chrome(service=Service(chrome_driver_path), options=options) myURLs = ["https://google.com", "https://x.com", "https://cnn.com"] for url in myURLs: driver.get(url) time.sleep(15) time.sleep(555) driver.quit()
额外说明:
如果确实需要使用远程调试模式(例如连接已打开的浏览器),需先手动启动Chrome并开启远程调试,再让Selenium连接到该实例,而非通过Selenium直接启动带该参数的浏览器。但根据你的需求,显然不需要此模式,直接移除参数即可解决问题。
内容的提问来源于stack exchange,提问作者Berk
相关产品推荐
相关产品推荐

