python-selenium报错解决大全

selenium安装教程:

linux - 安装Python-selenium+webdriver(Centos、ubuntu)-简枫博客
Windows - 安装Python-selenium+webdriver-简枫博客

报错列表

错误1:\'ascii\' codec can\'t encode characters in position 0-1: ordinal not in range(128)]

错误2 : session not created: DevToolsActivePort file doesn\'t exist)

错误1:\'ascii\' codec can\'t encode characters in position 0-1: ordinal not in range(128)

Ubuntu 将系统编码设置为UTF-8

出现这个报错是因为脚本中有中文输出,系统语言未支持中文,执行下面命令安装语言,

安装相关工具

sudo apt-get update
sudo apt-get install locales

安装 UTF-8 语言支持包

sudo locale-gen en_US.UTF-8

安装完成后,修改 /etc/default/locale 文件,将原内容清空,并输入以下内容

LANG="en_US.UTF-8"
LANGUAGE="en_US.UTF-8:"

修改 /etc/bash.bashrc 文件,在文件的最后添加以下内容:

export LANG="en_US.UTF-8"
export LANGUAGE="en_US.UTF-8:"

运行以下命令更新环境:

source /etc/bash.bashrc

错误2:session not created: DevToolsActivePort file doesn\'t exist)

当我们使用Selenium库在Python中进行网页自动化时,可能会遇到一个名为“DevToolsActivePort文件不存在”的异常。这个异常通常是因为Chrome浏览器在无界面运行时,无法找到DevToolsActivePort文件而导致的。

完整异常报错:

错误2 :session not created: DevToolsActivePort file doesn\'t exist) (The process started from chrome location /opt/google/chrome/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

解决方法一:使用Chrome Options

使用Chrome Options来指定DevToolsActivePort文件的位置。可以通过以下代码来设置Chrome Options

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-gpu')
options.add_argument('--remote-debugging-port=9222')
options.add_argument('--single-process')

driver = webdriver.Chrome(options=options)

解决方法二:设置环境变量

设置环境变量来指定DevToolsActivePort文件的位置。在Python中,可以通过以下代码设置环境变量:

import os

os.environ["DISPLAY"] = ":0"
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

    暂无评论内容