mac下 selenium + python 配置和入門


安裝

使用 pip install selenium

使用 Firefox

這里的版本信息:

python == 2.7
selenium == 3.4.3
firefox == 53.0.3

例程中的代碼:

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.

error

這里需要下載geckodriver,地址是這里:link

下載之后,放在PATH中:

PATH

再執行腳本就可以了。

gif

另外,如果出現錯誤:

Message: Unable to find a matching set of capabilities

將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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM