Backgroud: WebDriver中的find_element()方法用来查找元素,并返回WebElement对象。WebDriver 中最常用的方法。
好处: 使用find_element()的好处是方法名不会写死,定位方式可以通过参数传递,在一些框架中使用时会更加灵活。
借助 By 来传入定位方式,需要先引入,主要是为了防止定位方式写错。
| 定位方式 | By |
|---|---|
| id | By.ID |
| name | By.NAME |
| class_name | By.CLASS_NAME |
| tag_name | By.TAG_NAME |
| link_text | By.LINK_TEXT |
| partial_link_text | By.PARTIAL_LINK_TEXT |
| css_selector | By.CSS_SELECTOR |
| xpath | By.XPATH |
Eg: driver.find_element(By.ID, "kw") |
Code:
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
class TestCase(object):
def __init__(self):
self.driver = webdriver.Chrome() # from .chrome.webdriver import WebDriver as Chrome # noqa
self.driver.get('http://www.baidu.com')
self.driver.maximize_window() # 窗口最大化
sleep(1)
# driver.find_element()
def test_all(self):
self.driver.find_element(By.ID, value='kw').send_keys('Selenium')
self.driver.find_element_by_css_selector('#su').click()
sleep(2)
self.driver.quit()
if __name__ == '__main__':
case = TestCase()
case.test_all()