zoukankan      html  css  js  c++  java
  • selenium-xpath定位总结


    一、通过文本内容定位元素(div,td,span等)

    # 通过文本内容精准定位元素。可能由于页面内容有空格,经常定位不到元素
    driver.find_element_by_xpath('//div[text()="活动服务"]')   # 若要定位其它标签元素(如:td,span等),只需要替换div即可
    
    # 通过文本内容模糊定位元素
    driver.find_element_by_xpath('//div[contains(text(),"活动服务")]')

    二、通过元素tagName定位

    driver.find_element_by_xpath('//*[@placeholder="用户名"]').send_keys(username)
    driver.find_element_by_xpath('//*[@placeholder="密码"]').send_keys(password)

    三、通过已知元素定位元素

    # coding=utf-8
    
    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.get("http://www.baidu.com")
    driver.maximize_window()
    # 定位一个元素
    positioned_element = driver.find_element_by_id("form")
    
    # 通过已定位元素,定位子元素
    child_element = positioned_element.find_element_by_xpath("span[2]/input")
    child_element.send_keys("selenium")
    
    # 通过已定位元素,定位兄弟元素
    brother_element = positioned_element.find_element_by_xpath("../a/img[1]")
    brother_attribute = brother_element.get_attribute("title")
    print(brother_attribute)
    
    # 通过已定位元素,定位其它层级元素
    other_element = positioned_element.find_element_by_xpath("../../../div[3]/a[1]")
    other_attribute = other_element.get_attribute("href")
    print(other_attribute)
  • 相关阅读:
    Python爬虫实例:爬取豆瓣Top250
    爬虫协议 Tobots
    【Python 库】bs4的使用
    【Python 库】Selenium 的使用
    【Python 库】Selenium 浏览器驱动
    【Python 库】机器学习三剑客之 NumPy
    【Python】zip 函数的用法
    面试(一)-HashMap
    由树到数据库索引
    Win10下安装RabbitMQ以及基本知识学习
  • 原文地址:https://www.cnblogs.com/testlearn/p/12120502.html
Copyright © 2011-2022 走看看