zoukankan      html  css  js  c++  java
  • Selenium

    自动化测试工具,可以驱动浏览器执行特定的动作,如点击,下拉等。支持多种浏览器,爬虫中主要用来解决JavaScript渲染问题。

    准备工作
    使用之前需安装好谷歌浏览器以及ChromeDriver,以及python的第三方库Selenium

    1.查找节点

    from selenium.webdriver.common.by import By
    broser = webdriver
    browser.get('http://www.baidu.com')  #get()方法请求网页
    print(browser)    #
    * 查找单个节点
    
    input_first = browser.find_element_by_id('kw')
    input_second = browser.find_element_by_name('wd')
    input_third = browser.find_element_by_css_selector('#kw')
    input_four = browser.find_element_by_xpath('//*[@id="kw"]')
    input_five = browser.find_element(By.ID,'kw')  #通用查找方法,本质同browser.find_element_by_id()一样
    print(input_first,'
    ',input_second,'
    ',input_third,'
    ',input_four)
    运行结果一致,节点都为WebElement类型
    ![](https://img2020.cnblogs.com/blog/2053069/202101/2053069-20210112230320330-1206260551.png)
    * 查找多个节点
    
    以上方法只能得到匹配的第一个元素,如有多个节点符合条件,使用以下方法,返回值为列表:
    find_elements()
    find_elements_by_id()
    find_elements_by_name()
    find_elements_by_css_selector()
    find_element_by_xpath()
    find_elements_by_class_name()
    find_elements_by_tag_name()
    find_elements_by_link_text()
    

    2.节点交互

    Selenium可驱动浏览器执行一些操作,常见的有:
    输入文字:send_keys()
    清空文字:clear()
    点击按钮:click()

    from selenium import webdriverfrom selenium import webdriver
    
    browser = webdriver.Chrome()  #初始化浏览器对象
    browser.get('http://www.baidu.com')  #get()方法请求网页
    input = browser.find_element_by_id('kw')
    input.send_keys('热点')
    button = browser.find_element_by_xpath('//*[@id="su"]')
    button.click()
    
    

    3.获取元素信息

    print(input_first.get_attribute("name"))
    print(input_first.get_attribute("id"))
    print(input_first.text)
    print(input_first.tag_name)
    print(input_first.location)
    
  • 相关阅读:
    eas之得到当前选中的行id
    eas之关于数字精度的设置
    eas之使用值对象集合给ComboBox控件赋值
    eas之使用枚举给ComboBox控件赋值
    eas之删除类别时刷新当前结点的父结点,并定位到当前结点的父结点。
    eas之修改类别时刷新当前结点的父结点,并定位到当前结点
    eas之手工发送消息
    【阿里云开发】- 安装MySQL数据库
    【阿里云开发】- 安装JDK
    【开发笔记】- Java读取properties文件的五种方式
  • 原文地址:https://www.cnblogs.com/tingshu/p/13945985.html
Copyright © 2011-2022 走看看