mac下 selenium + python 配置和入門

安裝

使用 pip install seleniumpython

使用 Firefox

這裏的版本信息: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

error

這裏須要下載geckodriver,地址是這裏:linkajax

下載以後,放在PATH中:app

PATH

再執行腳本就能夠了。ui

gif

另外,若是出現錯誤:this

Message: Unable to find a matching set of capabilitiesgoogle

將Firefox更換到新的版本就能夠解決了。firefox

使用Safari

把代碼中的Firefox 換成 Safari 以後,不用配置,直接在個人mac上(macOS 10.12.5)上執行是沒有問題的。

Safari

代碼:

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()
相關文章
相關標籤/搜索