selenium3.x 踏坑记

来源:互联网 发布:网络语言膜法什么意思 编辑:程序博客网 时间:2024/06/06 02:19

Selenium 3.x 出来也有段时间了,有哪些坑呢?

有好长一段时间没有用selenium了。最近想用来做个web自动化的小工具。根据以往经验,firefox是不需要下载driver的。启动firefox. 立即抛出一个异常。

selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH

搜索得知:
1. selenium 3.x开始,webdriver/firefox/webdriver.py的init中,executable_path=”geckodriver”;而2.x是executable_path=”wires”
2. firefox 47以上版本,需要下载第三方driver

有没搞错,firefox也需要装driver了!
windows
下载解压后将getckodriver.exe复制到Firefox的安装目录下,
设置path,或者:

from selenium.webdriver.firefox.firefox_profile import FirefoxProfile driver = webdriver.Firefox(executable_path="C:\Program Files (x86)\Mozilla Firefox\geckodriver.exe")

mac:
可以用: brew install geckodriver
或者下载
把解压缩后的文件放到/usr/local/bin里面

from selenium import webdriverfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinarybinary = FirefoxBinary('/Applications/Firefox.app/Contents/MacOS/firefox-bin')browser = webdriver.Firefox(firefox_binary=binary)

Chrome就不用说了,直接下载一个driver, 一般直接放在python的路径下,找起来方便。

有的时候,加载图片,CSS等很慢,其实我们并不需要都加载完全,可以禁止掉
那么代码可以写成这样。

from selenium import webdriverimport sitefrom selenium.webdriver.chrome.options import Optionsfrom selenium.webdriver.firefox.firefox_profile import FirefoxProfile def get_python_location(self):        return site.getsitepackages()[0]    def get_driver(self):        if os.path.exists(os.path.join(self.get_python_location(), 'chromedriver.exe')):            chrome_options = Options()            chrome_options.add_experimental_option("prefs", {'profile.manage_default_content_settings.images': 2})            driver = webdriver.Chrome(os.path.join(self.get_python_location(), 'chromedriver.exe'), chrome_options=chrome_options)        else:            firefoxProfile = FirefoxProfile()            firefoxProfile.set_preference('permissions.default.stylesheet', 2)            firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')            firefoxProfile.set_preference('permissions.default.image', 2)            driver = webdriver.Firefox(firefoxProfile,executable_path="C:\Program Files (x86)\Mozilla Firefox\geckodriver.exe")        return driver

用phantomjs也可以,直接这样:

driver = webdriver.PhantomJS(service_args=['--load-images=false'])

这样,加载速度就可以快很多了。

更多精彩,请关注 微信公众号:python爱好部落

qrcode_for_gh_ca85abea157e_430.jpg

原创粉丝点击