随笔记录方便自己和同路人查阅。
#------------------------------------------------我是可耻的分割线-------------------------------------------
学习selenium自动化之前,最好先学习HTML、CSS、JavaScript等知识,有助于理解定位及操作元素的原理。关于python和selenium安装请自行搜索别的资料,
这里就不多做介绍了,所有例子均使用python3.6+selenium执行的。
#------------------------------------------------我是可耻的分割线-------------------------------------------
用By定位
针对前面介绍的8中定位方法,webdriver还提供了另外一套写法,即统一用find_element()方法,通过By来声明定位的方法,并且传入对应定位方法的定位参考。具体如下:
find_element(By.ID,”kw”)
find_element(By.NAME,”WD”)
find_element(By.CLASS_NAME,”s_ipt”)
find_element(By.TAG_NAME,”input”)
find_element(By.LINK_TEXT,”新闻”)
find_element(By.PARTIAL_LINK_TEXT,”新”)
find_element(By.XPATH,”//*[@class=’bg s_btn’]”)
find_element(By.CSS_SELECTOR,”span.bg s_btn_wr>input#su”)
find_element()方法只用于定位元素,它需要两个参数,第一个参数是定位的类型,由By提供;第二个参数是定位的具体方式。在使用By之前需要将By类导入。
from selenium.webdriver.common.by import By
通过查看WebDriver的底层实现代码发现它们其实是一回事儿,例如,find_element_by_id()方法的实现:
def find_element_by_id(self, id_): """Finds an element by id. :Args: - id\_ - The id of the element to be found. :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_id('foo') """ return self.find_element(by=By.ID, value=id_)
但WebDriver更推荐前面介绍的写法