赞
踩
本文记录了使用Python+Selenium+Chrome环境的常见问题。
是《Linux服务器上搭建Python+Selenium+Chrome的运行环境(静默模式、无图形)》的姊妹篇,安装方面的问题可参考该文章。
Python2.x的默认字符集编码是ASCII,因此会有很多字符集的问题。
SyntaxError: Non-ASCII character '\xe6' in file xxx.py on line 10, but no encoding
我脚本是在PyCharm中开发的,检查了一下文件字符集编码(菜单【File->Setting->Editor->File Encoding】):
发现工程配置是对的。考虑到python2.X的编码默认是ASCII,文件里有中文就必须要用utf-8编码(很多字符ASCII都不支持),于是采用另外一个方法:在文件开头标注:
#coding=utf-8
再重试就没有该报错了。
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 0: ordinal not in range(128)
这个问题是上个问题之后出现的,原因依然是编码问题,脚本中的中文无法识别。所以看起来文件本身指定编码并不能完全解决问题。
在不改变环境的前提下,尝试通过调整python编码解决问题:
value="值"
可改为value=u"值"
reload(sys); sys.setdefaultencoding('utf-8')
可以解决,但不推荐
- 这是一个类似后门的处理方式,部分情况下带来未知问题。
- Python3不支持该语法,一旦升级意味着重新改造。
代码变得过于复杂,编码和解码要保持一致。
字符集问题在任何语言中都是比较麻烦的存在,不同只是统一起来的成本高低。一旦涉及到跨环境或多进程,统一成本就会高起来。
上面通过修改代码,尽管解决了问题,但最推荐的方式还是升级到python3等高级版本,毕竟低版本还有很多其他问题。
如果要了解更多Python2.x的字符集编码问题,可以查看:
《Python2.x编码问题:UnicodeDecodeError: ‘ascii’ codec can’t decode byte in position : ordinal not in range》
关于升级到Python3,可以查看:
《Linux服务器中如何将Python2升级到Python3》
DevToolsActivePort file doesn't exist
没有配置无GUI运行,报错:
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
这里加上如下配置,让Chrome不以图形方式运行即可,怀疑是Linux服务器没有图形,所以会报错:
option = webdriver.ChromeOptions()
# 静默模式
option.add_argument('headless')
option.add_argument('--no-sandbox')
option.add_argument('--disable-gpu')
option.add_argument('--disable-dev-shm-usage')
更多参数可参考文章《Chrome Options详解》
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。