获取由 THEN if 条件换行的所有文本



html code

<div class=media>
<div class=11></div>
<div class=22></div>
<div class=media-content>
yes, this is the text<BR>
that i want to compare below
multiple line
</div>
</div>
<div class=media>
<div class=11></div>
<div class=22></div>
<div class=media-content>
and i want to compare above text multiple line
then if both same, i wanna break the loop
But it is not work
</div>
</div>

成功选择第一个元素(已通过 chropath 检查(

driver.find_elements_by_xpath('//div[@class="media"][last()]//div[@class="media-content"]')

成功选择第二个元素(已通过 chropath 检查(

driver.find_elements_by_xpath('//div[@class="media"][last()-1]//div[@class="media-content"]')

但是两个文本都不相同,但总是正确的然后中断。

if driver.find_elements_by_xpath('//div[@class="media"][last()]//div[@class="media-content"]').gettext() == driver.find_elements_by_xpath('//div[@class="media"][last()-1]//div[@class="media-content"]').gettext():
break

是的,这不是工作。

我想比较第一行和第二element(@class=media-content)中的文本(多行(

如果两个多行文本相同,我想停止循环。

但是两个文本都与您看到的不一样,但总是变为 TRUE 然后停止(中断(

我已成功选择项目(*with last[], last[]-1)但我不知道为什么它工作错误.....

有人可以对我的新手代码进行故障排除吗?
//text().gettext().text()

试试下面的代码。

items1=[item.text for item in driver.find_elements_by_xpath('//div[@class="media"][last()-1]//div[@class="media-content"]')]
items2=[item.text for item in driver.find_elements_by_xpath('//div[@class="media"][last()]//div[@class="media-content"]')]
if items1==items2:
print("pass")
else:
print("fail")

对我来说,anser 是(如果单div[@class@class="media-content"] 节点中有多个div[="media-content"] 元素(:

media_last = driver.find_elements_by_xpath('//div[@class="media"][last()]//div[@class="media-content"]')
media_last = [a.gettext() for a in media_last]
media_not_last =driver.find_elements_by_xpath('//div[@class="media"][last()-1]//div[@class="media-content"]')
media_not_last = [a.gettext() for a in media_not_last]
if media_last == media_not_last:
break

您无法在元素数组中获取方法 gettext

或者如果你想得到一个 jast 一个单一元素使用find_element_by_xpath方法

我使用您的html测试了以下内容,并得到了您期望的行为:

from selenium import webdriver
driver = webdriver.Chrome()
driver.get(r'file:///<path to local html file>') # Used local html file for testing purposes
el1 = driver.find_elements_by_xpath('//div[@class="media"][last()]//div[@class="media-content"]')
el2 = driver.find_elements_by_xpath('//div[@class="media"][last()-1]//div[@class="media-content"]')
if el1[0].text == el2[0].text:
print('Yes')
else:
print('No')

要了解的一件事是driver.find_elements_by_path()返回一个list对象。因此,即使您看起来正在定位页面中的特定元素,它们也存储在list对象中,如果您希望访问元素的文本,您应该以这种方式引用它们。

最新更新