如下图所示:
当定位元素时,我想获取指定的某一列的某一行的断言,如图我只想获取jiancha1的值,有同学会说:直接定位不就好了。但是我们知道,列表的数据会时刻变动的,不能靠定死的路径,那该怎么办呢?
我们可以在定位元素上下文章,首先,通过F12定位元素XPATH路径:
# 姓名:zc监察1 get_name_loc = (By.XPATH,"//div[@class='bs-example']/form/table/tbody/tr[1]/td[2]") # 姓名:jiancha1 get_name_loc = (By.XPATH,"//div[@class='bs-example']/form/table/tbody/tr[2]/td[2]")
对比一下,只有tr行不一样,所以如果想获取列表中某一列的所有数据,写下面的代码:
# 获取所有姓名 get_name_loc = (By.XPATH,"//div[@class='bs-example']/form/table/tbody/tr/td[2]")
然后通过循环得到列表数据:
get_name_loc = (By.XPATH,"//div[@class='bs-example']/form/table/tbody/tr/td[2]") def getListName(self,realname): ''' 获取列表真实姓名 :param realname: 真实姓名 :return: getRealname ''' # 查询最新输入的姓名 sleep(0.5) getRealname = functions.AllFuncions().getNewName(realname)[2]
============重点============= # 定位姓名元素 names = self.find_elements(*self.get_name_loc) lists = [] for i in names: lists.append(i.text) ============重点============= # 对比数据库数据与列表数据 if getRealname in lists: return getRealname else: return None
这样就大功告成啦!获取数据库中想要的字段值跟列表中的数据进行对比,如果存在则把这个值进行断言。
感谢参考文章:《python3+selenium获取列表某一列的值》