python2.7+webdriver搭建

1. 安装python:
 http://www.python.org/getit/releases/2.7.2/

2. 安装selenium

http://pypi.python.org/pypi/selenium
 
3. 解压selenium-2.21.2,cd到解压目录执行:python setup.py install
 

4. 安装完成后,接下来写段小代码测试下是否可用:

from selenium import webdriver

from selenium.common.exceptions import NoSuchElementException

from selenium.webdriver.common.keys import Keys

import time

 

browser = webdriver.Firefox() # Get local session of firefox

browser.get("http://www.yahoo.com") # Load page

print browser.title

assert "Yahoo!" in browser.title

elem = browser.find_element_by_name("p") # Find the query box

elem.send_keys("seleniumhq" + Keys.RETURN)

time.sleep(0.2) # Let the page load, will be added to the API

try:

    browser.find_element_by_xpath("//a[contains(@href,'http://seleniumhq.org')]")

except NoSuchElementException:

    assert 0, "can't find seleniumhq"

browser.close()

如果以类的形式写testcase,还可以这样:

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import Select

from selenium.common.exceptions import NoSuchElementException

import unittest, time, re

 

class Test(unittest.TestCase):

    def setUp(self):

        self.driver = webdriver.Firefox()

        self.driver.implicitly_wait(30)

        self.base_url = "http://www.baidu.com/"

        self.verificationErrors = []

   

    def test_(self):

        driver = self.driver

        driver.get(self.base_url + "/")

        driver.find_element_by_id("kw").clear()

        driver.find_element_by_id("kw").send_keys("sina")

        driver.find_element_by_id("su").click()

   

    def is_element_present(self, how, what):

        try: self.driver.find_element(by=how, value=what)

        except NoSuchElementException, e: return False

        return True

   

    def tearDown(self):

        self.driver.quit()

        self.assertEqual([], self.verificationErrors)

 

if __name__ == "__main__":

    unittest.main()

你可能感兴趣的:(webdriver)