python+selenium遍历某一个标签中的内容

一、python+selenium遍历某一个标签中的内容

举个例子:我要获取列表标签

  • 的内容

    根据python+selenium定位到列表整体,使用for循环获取列表文本;可用于校验列表是否存在你需要的文本内容

    1.获取内容不包含嵌套层列表

    给出代码:

    复制代码

    from selenium import webdriver
    import time
    
    d = webdriver.Chrome()
    d.maximize_window()  # 窗口最大化
    ###登录某网站
    d.get('http://xx.xxx.xx.xx:xxxx/')
    d.find_element_by_xpath('//*[@id="userName"]').send_keys('xxx')
    d.find_element_by_xpath('//*[@id="userPwd"]').send_keys('xxx')
    d.find_element_by_xpath('//*[@id="login"]').click()
    time.sleep(2)
    ###切换表单,进入到操作页面
    d.find_element_by_xpath('//*[@id="menu_ul"]/li[5]/a').click()
    d.switch_to_frame('mainframe2')
    d.find_element_by_xpath('//*[@id="nav-accordion"]/li[2]/a').click()
    d.switch_to_frame('mainframe')
    d.switch_to_frame('vehIframe')
    ###定位到要获取标签的顶级元素,并使用for循环获取
    names = d.find_elements_by_xpath('//*[@id="vehGroupTree_1"]')
    lists = []
    for i in names:
        a = i.text
        lists.append(a)
        print(a, i.get_attribute("href"))  # 打印遍历标签出来的内容和获取href属性的内容
    print(lists)
    print(lists[0].split('\n'))
    print(len(lists[0].split('\n')))  # 打印列表元素数目

    复制代码

     注意:有些列表不仅仅包含嵌套列表,还有扩展项(指的是“+”可以展开的那种),这里我们获取的内容只是最外层内容(获取那一层内容取决于定位元素names = d.find_elements_by_xpath('//*[@id="vehGroupTree_1"]')),使用这种方式要想获取嵌套列表的内容,还需要逐层展开(点开)嵌套层才行,否则该元素是隐藏起来的。

    你可能感兴趣的:(python+selenium遍历某一个标签中的内容)