我一直在尝试使用此代码运行 chromdriver
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
service = Service(executable_path=r'C:\Anfield\Archive\Chromedriver\chromedriver-win64\chromedriver-win64\chromedriver.exe')
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
url = 'https://shopee.co.th'
driver.get(url)
并且总是收到此错误
[4124:24652:1217/120010.859:ERROR:socket_manager.cc(147)] 无法解析 stun.l.google.com 的地址。错误代码:-105 [9408:22992:1217/120011.263:错误:command_buffer_proxy_impl.cc(331)] WaitForGetOffsetInRange后GPU状态无效。
chromedriver 只会出现一会儿,然后就会消失。有谁知道可能出什么问题吗?
我一直在网上搜索,将错误状态放入搜索框中,但到目前为止我还没有找到正确的解决方案
该错误与 WebRTC 和 GPU 加速有关,可以通过修改 Chrome 选项来解决。我对代码做了一些更改:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time
def setup_chrome_driver():
# Create ChromeOptions instance
options = Options()
# Add various options to make the browser more stable
options.add_argument('--disable-gpu') # Disable GPU hardware acceleration
options.add_argument('--disable-dev-shm-usage') # Overcome limited resource problems
options.add_argument('--no-sandbox') # Bypass OS security model
options.add_argument('--disable-web-security') # Disable web security
options.add_argument('--allow-running-insecure-content') # Allow running insecure content
options.add_argument('--disable-webrtc') # Disable WebRTC
# Optional: Run in headless mode if you don't need to see the browser
# options.add_argument('--headless')
# Set up the service
service = Service(executable_path=r'C:\Anfield\Archive\Chromedriver\chromedriver-win64\chromedriver-win64\chromedriver.exe')
try:
# Create the driver
driver = webdriver.Chrome(service=service, options=options)
# Set page load timeout
driver.set_page_load_timeout(30)
return driver
except Exception as e:
print(f"Error setting up ChromeDriver: {str(e)}")
return None
# Usage example
def main():
driver = setup_chrome_driver()
if driver:
try:
url = 'https://shopee.co.th'
driver.get(url)
# Add a small delay to keep the browser open
time.sleep(5)
# Your scraping code here
except Exception as e:
print(f"Error during execution: {str(e)}")
finally:
# Always close the driver properly
driver.quit()
if __name__ == "__main__":
main()
尝试一下代码,看看是否能解决问题。如果浏览器仍然关闭得太快,请尝试以下操作:
time.sleep(5)
持续时间driver.quit()
调用input("Press Enter to close...")
之前添加driver.quit()
来控制浏览器何时关闭还要确保:
pip install --upgrade selenium
)。我希望这有帮助