Mac 下python + Selenium + PhantomJS自动登录

2017-4-9 Frank Python

安装

  1. Selenium
    sudo pip install selenium
    
  2. PhantomJS
    brew install phantomjs
    
  3. 下载chromedriver
    http://chromedriver.storage.googleapis.com/index.html
    我这下载的chromedriver_mac64.zip,将解压后的chromedriver移动到/usr/local/bin目录下 。

    示例

    # -*- coding: utf-8 -*-
    from selenium import webdriver
    import time
    def login(username,pwd):
     driver = webdriver.PhantomJS()
     # driver = webdriver.Chrome()
     driver.get("http://mail.163.com")
     print "浏览器最大化"
     driver.maximize_window()  #将浏览器最大化显示
     driver.set_window_size(1000, 800)  #参数数字为像素点
     # wait = ui.WebDriverWait(driver, 60)
     # wait.until(lambda dr: dr.find_element_by_name('email').is_displayed())
     #selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"name","selector":"email"}
     # 因为登录窗口变成了iframe
     frame = driver.find_element_by_xpath('//iframe[@id="x-URS-iframe"]')
     driver.switch_to.frame(frame)
     time.sleep(1)
     driver.find_element_by_name("email").send_keys(username)
     driver.find_element_by_name("password").send_keys(pwd)
     driver.find_element_by_id("dologin").click()
     # wait.until(lambda dr: dr.find_element_by_id('login_area').is_displayed())
     #返回(后退)
     # driver.back()
     #前进
     # driver.forward()
     time.sleep(3)
     #截屏
     driver.save_screenshot('screen.png')
     driver.quit()
    #执行该文件的主过程
    if __name__ == '__main__':
     login("username","password")
    

如果你运行了上面的程序,可能会报错,那就来瞧瞧这个帖子吧selenium +phantomjs 登录126邮箱 iframe定位问题

参考
http://selenium-python.readthedocs.io/installation.html
Docker环境下运行Python + Selenium + Chrome

发表评论 登录

Top