使用 pip install selenium
。python
这里的版本信息:git
python == 2.7 selenium == 3.4.3 firefox == 53.0.3
例程中的代码:github
from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0 from selenium.webdriver.firefox.firefox_binary import FirefoxBinary # add by self import time # binary = FirefoxBinary('/Applications/Firefox.app') # driver = webdriver.Firefox(firefox_binary=binary) # Create a new instance of the Firefox driver driver = webdriver.Firefox( ) # go to the google home page driver.get("http://www.google.com") # the page is ajaxy so the title is originally this: print driver.title # find the element that's name attribute is q (the google search box) inputElement = driver.find_element_by_name("q") # type in the search inputElement.send_keys("cheese!") # submit the form (although google automatically searches now without submitting) inputElement.submit() try: # we have to wait for the page to refresh, the last thing that seems to be updated is the title WebDriverWait(driver, 10).until(EC.title_contains("cheese!")) # You should see "cheese! - Google Search" print driver.title finally: time.sleep(4) driver.quit()
执行以后首先发现是 lenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
:web
这里须要下载geckodriver
,地址是这里:linkajax
下载以后,放在PATH中:app
再执行脚本就能够了。ui
另外,若是出现错误:this
Message: Unable to find a matching set of capabilities
google
将Firefox更换到新的版本就能够解决了。firefox
把代码中的Firefox
换成 Safari
以后,不用配置,直接在个人mac上(macOS 10.12.5)上执行是没有问题的。
代码:
from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0 import time # Create a new instance of the Firefox driver driver = webdriver.Safari() # go to the google home page driver.get("http://www.google.com") # the page is ajaxy so the title is originally this: print driver.title # find the element that's name attribute is q (the google search box) inputElement = driver.find_element_by_name("q") # type in the search inputElement.send_keys("cheese!") # submit the form (although google automatically searches now without submitting) inputElement.submit() try: # we have to wait for the page to refresh, the last thing that seems to be updated is the title WebDriverWait(driver, 10).until(EC.title_contains("cheese!")) # You should see "cheese! - Google Search" print driver.title finally: time.sleep(4) driver.quit()