gpt4 book ai didi

python - 是否可以使用 XPATH 和 Selenium 从 Python 中的特定 div 开始计数?

转载 作者:行者123 更新时间:2023-12-01 00:54:43 25 4
gpt4 key购买 nike

我有 80 个 div,每个 div(在我们的例子中为 24、27、30 类)包含 2 个子元素。

是否可以从第 24 行(不包括 child )开始计数,然后继续计算其下面的行? (仅使用 XPATH,而不是 CSS 选择器;))

<div class="container">
... # dots signify the divs before it
<div class="24">
<div class="25"></div>
<div class="26"></div>
</div>
<div class="27">
<div class="28"></div>
<div class="29"></div>
</div>
<div class="30">
<div class="31"></div>
<div class="32"></div>
</div>
... # divs after it
</div>

有没有类似的东西:

比方说:

x = 0
all_the_divs = driver.find_elements_by_xpath("//div/*")
while x < len(all_the_divs):
# do something
pass
if x == 24:
# catch all the divs under 24 (excluding 24)
# something like:
divs_under_x = len(driver.find_elements_by_xpath("//div/div[" + str(x) + "]::"))
# or
divs_under_x = len(driver.find_elements_by_xpath("//div/following-sibling::div[" + str(x) + "]*"))
break
x += 1

输出:长度应为 2(第 27 类和第 30 类没有他们的 child )非常感谢。

最佳答案

这里是:

from lxml import etree

data = [your data above]


tree = lxml.etree.fromstring(data, parser=lxml.etree.HTMLParser())
targets = tree.xpath("*//div[(position()=2 or position()=3) and descendant::div]")
for i in targets:
for child in i.getchildren():
child.getparent().remove(child)
print(etree.tostring(i).decode().replace('\n','').strip())

输出:

<div class="27">        </div>
<div class="30"> </div>

希望这至少是您正在寻找的大致方向......

关于python - 是否可以使用 XPATH 和 Selenium 从 Python 中的特定 div 开始计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com