硒 while 循环不工作

2024-03-18

所以我开始掌握 while 循环的窍门,但是当在 selenium 代码上使用 while 循环时,我遇到了不足。

我几乎尝试将一个任务复制 10 次,代码如下

Main.py

from selenium import webdriver
from selenium.webdriver.common.keys import Keys


driver = webdriver.Chrome()
driver.get('https://orlando.craigslist.org/search/cta')

owl = driver.find_element_by_xpath('//*[@id="sortable-results"]/ul/li/p/a')
res = 1

while res < 10:
    owl2 = owl.click()
    driver.find_element_by_xpath('/html/body/section/header/nav/ul/li[3]/p/a').click()

    res = res + 1

这是错误

回溯(最近一次调用最后一次): 文件“main.py”,第 12 行,位于 owl2 = owl.click() 文件“/Library/Python/2.7/site-packages/selenium/webdriver/remote/webelement.py”, 第 77 行,点击 self._execute(Command.CLICK_ELEMENT) 文件“/Library/Python/2.7/site-packages/selenium/webdriver/remote/webelement.py”, 第 491 行,在 _execute 中 返回 self._parent.execute(命令,参数) 文件“/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py”, 第238行,执行中 self.error_handler.check_response(响应) 文件“/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py”, 第 193 行,在 check_response 中 引发异常类(消息、屏幕、堆栈跟踪) selenium.common.exceptions.StaleElementReferenceException:消息:过时的元素引用:元素未附加到页面 文档 (会话信息:chrome=56.0.2924.87) (驱动程序信息:chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),平台=Mac OS X 10.11.2 x86_64)

有什么建议 ?


每次 DOM 更改或刷新时driver丢失了之前定位的元素,从而导致了错误。

StaleElementReferenceException:消息:过时的元素引用: 元素未附加到页面文档

您需要重新定位它们才能与它们交互。此外,click()不返回任何值,因此您不能将其分配给任何东西

res = 1
while res < 10:
    owl = driver.find_element_by_xpath('//*[@id="sortable-results"]/ul/li/p/a')
    owl.click()
    driver.find_element_by_xpath('/html/body/section/header/nav/ul/li[3]/p/a').click()
    res = res + 1

Edit

With for循环查找所有项目,您可以将这些项目定位到列表中并按索引单击

size = len(driver.find_elements_by_xpath('//*[@id="sortable-results"]/ul/li/p/a'))
for i in range(0, size):
    owl = driver.find_elements_by_xpath('//*[@id="sortable-results"]/ul/li/p/a')
    owl[i].click()
    driver.find_element_by_xpath('/html/body/section/header/nav/ul/li[3]/p/a').click()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

硒 while 循环不工作 的相关文章

随机推荐