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

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

查看所有标签

猜你喜欢:

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

Tales from Facebook

Tales from Facebook

Daniel Miller / Polity Press / 2011-4-1 / GBP 55.00

Facebook is now used by nearly 500 million people throughout the world, many of whom spend several hours a day on this site. Once the preserve of youth, the largest increase in usage today is amongst ......一起来看看 《Tales from Facebook》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具