Python+Selenium實(shí)現(xiàn)列表元素的查找及刪除
獲取列表(單頁)全部數(shù)據(jù)
# 獲取列表單頁全部數(shù)據(jù)
def get_table_content(self, table_tbody):
"""
獲取列表單頁全部數(shù)據(jù)
:param table_tbody: 列表定位tbody
:return:
"""
time.sleep(1)
list_1 = []
# 表格定位路徑
element = self.driver.find_element(By.XPATH, table_tbody)
# 獲取每一行數(shù)據(jù)tr
table_tr_list = element.find_elements(By.TAG_NAME, "tr")
# 按行查詢表格的數(shù)據(jù),取出的數(shù)據(jù)是一整行
for tr in table_tr_list:
# tr.text獲取表格每行的文本內(nèi)容、切割字符串
# list_2 = tr.get_attribute('textContent')
list_2 = (tr.text).split()
list_1.append(list_2)
return list_1
刪除某行元素
# 刪除某行元素
def del_table_data(self, table_tbody, row, btn_fixed, del_sucessful_info):
"""
刪除列表元素
:param table_tbody: 列表定位
:param row: 刪除數(shù)據(jù)所在行
:param btn_fixed: (點(diǎn)擊刪除后,彈出框中區(qū)確認(rèn)刪除按鈕)
:param del_sucessful_info: (刪除成功后,提示信息)
:return:
"""
# 表格定位路徑
element = self.driver.find_element(By.XPATH, table_tbody)
# 獲取每一行數(shù)據(jù)tr
table_tr_list = element.find_elements(By.TAG_NAME, "tr")
try:
# 對(duì)應(yīng)行查找“刪除”按鈕并點(diǎn)擊
table_tr_list[row].find_element(By.XPATH, ".//td//span[text()='刪除']").click()
# 如果有是否確認(rèn)刪除的彈框,點(diǎn)擊“確定”按鈕
self.click(btn_fixed, doc="點(diǎn)擊確認(rèn)按鈕,刪除數(shù)據(jù)")
time.sleep(1)
# 獲取刪除后的提示信息:“刪除成功”
ret_del_info = self.get_element_text(del_sucessful_info)
time.sleep(0.5)
except:
# 如果在對(duì)應(yīng)行未找到“刪除”按鈕,則說明該數(shù)據(jù)不允許刪除
ret_del_info = "該數(shù)據(jù)不允許刪除,請(qǐng)重新操作!"
return ret_del_info
查找并刪除元素(目前僅支持刪除單條數(shù)據(jù),循環(huán)刪除待繼續(xù)研究)
# 查找并刪除元素
def find_and_del_table_data(self, table_tbody, queryContent, btn_fixed, del_sucessful_info):
"""
循環(huán)遍歷table數(shù)據(jù),確定查詢數(shù)據(jù)的位置
:param table_tbody: 列表表格定位
:param queryContent: 查詢內(nèi)容
:param btn_fixed: (點(diǎn)擊刪除后,彈出框中區(qū)確認(rèn)刪除按鈕)
:param del_sucessful_info:(刪除成功后,提示信息)
:return:
"""
# 調(diào)用獲取列表(單頁)全部數(shù)據(jù)函數(shù)
arr_data = self.get_table_content(table_tbody)
ret_info = ""
del_info = ""
# 嵌套for循環(huán)查找列表中元素的位置
for i in range(len(arr_data)):
for j in range(len(arr_data[i])):
if queryContent == arr_data[i][j]:
ret_info = "'{}'坐標(biāo)位置:({},{})".format(queryContent, i + 1, j + 1)
ret_row = i
print(ret_info)
# 調(diào)用刪除元素函數(shù)
del_info = self.del_table_data(table_tbody, ret_row,
btn_fixed, del_sucessful_info)
print(del_info)
time.sleep(2)
if ret_info != "" and del_info != "該數(shù)據(jù)不允許刪除,請(qǐng)重新操作!":
ret_info = "'{}'元素存在且刪除成功!??!".format(queryContent)
return ret_info
elif ret_info != "" and del_info == "該數(shù)據(jù)不允許刪除,請(qǐng)重新操作!":
ret_info = "'{}'元素不允許刪除?。?!".format(queryContent)
return ret_info
else:
ret_info = "'{}'元素不存在,請(qǐng)重新查找?。?!".format(queryContent)
return ret_info
結(jié)果示例
文章來源地址http://www.zghlxwxcb.cn/news/detail-546428.html
文章來源:http://www.zghlxwxcb.cn/news/detail-546428.html
到了這里,關(guān)于Python+Selenium實(shí)現(xiàn)列表元素的查找定位及刪除操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!