gpt4 book ai didi

python - selenium while 循环不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 13:33:37 24 4
gpt4 key购买 nike

所以我开始掌握 while 循环的窍门,但是当在 selenium 代码上使用 while 循环时,我会做空。

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

主.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

这里是错误

Traceback (most recent call last): File "main.py", line 12, in owl2 = owl.click() File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webelement.py", line 77, in click self._execute(Command.CLICK_ELEMENT) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webelement.py", line 491, in _execute return self._parent.execute(command, params) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 238, in execute self.error_handler.check_response(response) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 193, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: chrome=56.0.2924.87) (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Mac OS X 10.11.2 x86_64)

有什么建议吗?

最佳答案

每次 DOM 更改或刷新时,驱动程序 都会丢失它之前定位的元素,从而导致错误。

StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

您需要重新定位它们才能与它们互动。此外,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

使用 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()

关于python - selenium while 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42738189/

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