Python Selenium:循环访问嵌入到<li>元素中的href

2024-10-06 08:06:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分析这样一个组织的网页:

<nav class="sidebar-main">
    <div class="sidebar">Found 3 targets</div>
        <ul><li><a href="#target1" class="current"><span>target1</span></a></li>
        <li><a href="#target2" ><span>target2</span></a></li>
        <li><a href="#target3"><span>target3</span></a></li></ul>
</nav>

我的目标是循环遍历每个列表元素,在过程中单击每个元素:

^{pr2}$

我一直收到错误:

Message: The element reference of <li> stale either the element is no 
longer attached to the DOM or the page has been refreshed.

现在只点击了一个链接,显然selenium无法在页面刷新时定位后续元素,我该如何解决这个问题?


Tags: thediv元素网页lielementulclass
1条回答
网友
1楼 · 发布于 2024-10-06 08:06:12

单击第一个链接后,导航到新页面或刷新页面。您需要跟踪元素列表,再次找到列表元素,然后单击所需的元素。如果页面已更改,则还需要导航回原始页面。在

你可以试试下面的方法

sidebar = browser.find_element_by_class_name('sidebar-main')
elementList = sidebar.find_elements_by_tag_name("li")
for i in range(len(elementList)):
    element = browser.find_element_by_class_name('sidebar-main').find_elements_by_tag_name("li")[i]
    element.click()

相关问题 更多 >