首页 文章

硒虽然循环不起作用

提问于
浏览
3

所以我开始得到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(命令,params)文件“/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py”,第238行,执行self.error_handler.check_response(response)文件“/Library/Python/2.7/ site-packages / selenium / webdriver / remote / errorhandler.py“,第193行,在check_response中引发exception_class(message,screen,stacktrace)selenium.common.exceptions.StaleElementReferenceException:消息:陈旧元素引用:元素未附加到页面document(会话信息:chrome = 56.0.2924.87)(驱动程序信息:chromedriver = 2.27.440174(e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform = Mac OS X 10.11.2 x86_64)

有什么建议 ?

2 回答

  • 4

    每当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
    

    编辑

    对于所有项目使用 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()
    
  • 2

    错误消息给了我们一个线索:

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

    这里发生的是你点击一个链接,并导航到另一个页面,因此,你得到陈旧的元素,因为你在一个不同的页面 . 您将需要导航回同一页面,尝试这样的事情:

    driver.execute_script("window.history.go(-1)")
    

    在click()事件之后 .

相关问题