selenium元素操作封装

栏目: 编程工具 · 发布时间: 6年前

  • id
  • name
  • class name
  • tag name
  • link text
  • partial link text
  • xpath
  • css selector

这8种定位方式在Python selenium中所对应的方法为:

  • find_element_by_id()
  • find_element_by_name()
  • find_element_by_class_name()
  • find_element_by_tag_name()
  • find_element_by_link_text()
  • find_element_by_partial_link_text()
  • find_element_by_xpath()
  • find_element_by_css_selector()

常用元素定位封装

def _locate_element(self, selector):
    """
    to locate element by selector
    :arg
    selector should be passed by an example with "i,xxx"
    "x,//*[@id='langs']/button"
    :returns
    DOM element
    """
    if self.by_char not in selector:
        return self.base_driver.find_element_by_id(selector)

    selector_by = selector.split(self.by_char)[0].strip()
    selector_value = selector.split(self.by_char)[1].strip()
    if selector_by == "i" or selector_by == 'id':
        element = self.base_driver.find_element_by_id(selector_value)
    elif selector_by == "n" or selector_by == 'name':
        element = self.base_driver.find_element_by_name(selector_value)
    elif selector_by == "c" or selector_by == 'class_name':
        element = self.base_driver.find_element_by_class_name(selector_value)
    elif selector_by == "l" or selector_by == 'link_text':
        element = self.base_driver.find_element_by_link_text(selector_value)
    elif selector_by == "p" or selector_by == 'partial_link_text':
        element = self.base_driver.find_element_by_partial_link_text(selector_value)
    elif selector_by == "t" or selector_by == 'tag_name':
        element = self.base_driver.find_element_by_tag_name(selector_value)
    elif selector_by == "x" or selector_by == 'xpath':
        element = self.base_driver.find_element_by_xpath(selector_value)
    elif selector_by == "s" or selector_by == 'css_selector':
        element = self.base_driver.find_element_by_css_selector(selector_value)
    else:
        raise NameError("Please enter a valid type of targeting elements.")

    return element

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Viral Loop

Viral Loop

Adam L. Penenberg / Tantor Media / 2009-10-27 / USD 34.99

From Google to Facebook, a respected journalist delves into how a "viral loop" can make an online business a success.一起来看看 《Viral Loop》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具