[Selenium][Notes]Day2:详解find_element()

254 阅读1分钟

Backgroud: WebDriver中的find_element()方法用来查找元素,并返回WebElement对象。WebDriver 中最常用的方法。

好处: 使用find_element()的好处是方法名不会写死,定位方式可以通过参数传递,在一些框架中使用时会更加灵活。

借助 By 来传入定位方式,需要先引入,主要是为了防止定位方式写错。

定位方式By
idBy.ID
nameBy.NAME
class_nameBy.CLASS_NAME
tag_nameBy.TAG_NAME
link_textBy.LINK_TEXT
partial_link_textBy.PARTIAL_LINK_TEXT
css_selectorBy.CSS_SELECTOR
xpathBy.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()