zoukankan      html  css  js  c++  java
  • 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 Firefoxgeckodriver.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 Firefoxgeckodriver.exe")
            return driver
    

    用phantomjs也可以,直接这样:

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

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

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

    qrcode_for_gh_ca85abea157e_430.jpg

  • 相关阅读:
    题6:利用二进制表示浮点数
    题5:将整数二进制形式的奇偶位交换
    如何访问别的主机共享的文件
    排序算法------插入排序
    centos7进入单用户模式修改root密码
    排序算法------选择排序法
    排序算法------冒泡排序法
    题4:判断一个数是否时2的整数次方
    LockSupport类
    synchronized原理及锁膨胀
  • 原文地址:https://www.cnblogs.com/lucklly/p/7243454.html
Copyright © 2011-2022 走看看