使用这些命令,我会多次打印出“ Hello”一词
one=driver.find_elements_by_xpath("any")
for two in one:
if two.text=='three'
print('Hello')
else:
print('Bye')
我该如何更改代码,以便如果所有元素==“三个”都打印一次“ Hi”,并且有一个元素! =“三”,它被打印一次“再见”
答案 0 :(得分:3)
您可以使用any()
one = driver.find_elements_by_xpath("any")
if any(two.text != 'three' for two in one):
print('Bye')
else:
print('Hello')
答案 1 :(得分:2)
您可以设置one
并比较结果
one = driver.find_elements_by_xpath("any")
two = {_.text for _ in one}
if len(two) == 1 and two[0] == 'three':
print('hi')
else:
print('bye')
有效地,这需要('three', 'three', 'three')
并将其转换为{'three'}
或需要('three', 'three', 'not three')
并将其转换为{'three', 'not three'}
。然后,您可以查看它是否只有一个元素长,并且该元素是否为'three'
。
希望如果需要这种解释会有所帮助。
答案 2 :(得分:2)
如果您使用all()
而不是any()
,则更加清楚:
one=driver.find_elements_by_xpath("any")
if all(two.text == 'three' for two in one):
print('Hello')
else:
print('Bye')
答案 3 :(得分:1)
一个函数可以做到这一点:
one=driver.find_elements_by_xpath("any")
def helloBye(one):
for two in one:
if two.text!="three":
print("Bye")
return
print("Hello")
return
helloBye(one)
答案 4 :(得分:0)
对不起,我之前听不懂你的问题,应该这样做:
one=driver.find_elements_by_xpath("any")
i = 0
for two in one:
if two.text=='three'
i = i + 1
if and i==len(one)
print('Hello')
else:
print('Bye')
break
答案 5 :(得分:0)
这可以通过多种方式实现:
在这里,我给你两种方法。
第一个也是最简单的方法是维护一个计数器并检查该计数器。这可以通过以下方式实现:
counter_three = 0
counter_not_three = 0
for two in one:
if two.text=='three':
if counter_three == 0:
counter_three = counter_three + 1
print('Hello')
else:
if counter_not_three == 0:
print('Bye')
counter_not_three = counter_not_three + 1
第二种方法如下:
a = [{"text": "three"},{"text": "three"}, {"text": "three"}, {"text": "three"}, {"text": "two"}]
a_list = set(map(lambda x: x["text"], a))
for x in a_set:
if x == 'three':
print('Hello')
else:
print('Bye')