python+selenium遍歷某一個標簽中的內容


一、python+selenium遍歷某一個標簽中的內容

舉個例子:我要獲取列表標簽<li></li>的內容

根據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"]')),使用這種方式要想獲取嵌套列表的內容,還需要逐層展開(點開)嵌套層才行,否則該元素是隱藏起來的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM