selenium3.x 踏坑记

 

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 FirefoxBinary
binary = FirefoxBinary('/Applications/Firefox.app/Contents/MacOS/firefox-bin')
browser = webdriver.Firefox(firefox_binary=binary)

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

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

from selenium import webdriver
import site
from selenium.webdriver.chrome.options import Options
from 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

 

转载于:https://www.cnblogs.com/lucklly/p/7243454.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值