Python的web自动化学习(四)Selenium的显性等待(元素定位)

引言:

Selenium的显性等待,其常用的定位方法介绍,后面持续更细具体用法

示例如下:

<input type="text" class="s_ipt" name="wd" id="kw" maxlength="100" autocomplete="off">

ID定位

wait.until(EC.visibility_of_element_located((By.ID, 'kw')))

Name定位:

wait.until(EC.visibility_of_element_located((By.NAME, 'wd')))

Class定位:

wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 's_ipt')))

Tag定位:

wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'element_tag')))

Link Text定位:

wait.until(EC.visibility_of_element_located((By.LINK_TEXT, 'link_text')))

Partial Link Text定位: Link Text包含定位:

wait.until(EC.visibility_of_element_located((By.PARTIAL_LINK_TEXT, 'partial_link_text')))

CSS Selector定位:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'css_selector')))

XPath定位:

wait.until(EC.visibility_of_element_located((By.XPATH, 'xpath')))

层级定位:

parent_element = driver.find_element(By.XPATH, 'parent_xpath')
wait.until(EC.visibility_of_element_located((By.XPATH, 'child_xpath')), parent_element)

多个条件组合定位:

wait.until(EC.visibility_of_element_located((By.XPATH, 'xpath')) and EC.element_to_be_clickable((By.ID, 'element_id')))

标签属性定位:

wait.until(EC.visibility_of_element_located((By.XPATH, '//tag[@attribute="value"]')))

元素文本定位:

wait.until(EC.visibility_of_element_located((By.XPATH, '//*[text()="element_text"]')))

元素属性值包含定位:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[attribute*="value"]')))

元素属性值以定位:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[attribute^="value"]')))

元素属性值结尾定位:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[attribute$="value"]')))

元素文本包含定位:

wait.until(EC.visibility_of_element_located((By.XPATH, '//*[contains(text(), "element_text")]')))

属性值正则匹配定位:

wait.until(EC.visibility_of_element_located((By.XPATH, '//*[matches(@attribute, "regex_pattern")]')))

子元素定位:

parent_element = driver.find_element(By.XPATH, 'parent_xpath')
wait.until(EC.visibility_of_element_located((By.XPATH, 'child_xpath')), parent_element)

元素索引定位:

wait.until(EC.visibility_of_element_located((By.XPATH, '(//tag)[index]')))

兄弟元素定位:

wait.until(EC.visibility_of_element_located((By.XPATH, 'preceding-sibling::tag')))

父元素定位:

wait.until(EC.visibility_of_element_located((By.XPATH, 'parent::tag')))

祖先元素定位:

wait.until(EC.visibility_of_element_located((By.XPATH, 'ancestor::tag')))

子元素索引定位:

wait.until(EC.visibility_of_element_located((By.XPATH, 'parent_xpath/tag[index]')))

元素属性值不等于定位:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[attribute!="value"]')))

元素属性值包含多个定位:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[attribute~="value1"][attribute~="value2"]')))

元素属性值开始定位:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[attribute^="value"]')))

以上是常用selenium的基本定位的方法,后面持续更新具体结合实际操作用法

你可能感兴趣的:(python,前端,自动化)