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.
:
这里需要下载geckodriver
,地址是这里:link
下载之后,放在PATH中:
再执行脚本就可以了。
另外,如果出现错误:
Message: Unable to find a matching set of capabilities
将Firefox更换到新的版本就可以解决了。
使用Safari
把代码中的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()