如何与硒中的click()循环?

我想单击Facebook上每个成员的个人资料,但是在循环播放时出现错误。

这是我的代码:

def open(link):
    try:
        driver.get(link)
    except:
        print('no internet access')

def OpenProfileMember():
    open('https://mbasic.facebook.com/browse/group/members/?id=1600319190185424')
    find = driver.find_elements_by_class_name('bn')
    for x in find:
        if x != find[0]:
            x.click()
            time.sleep(3)
            driver.back()
        else:
            continue
OpenProfileMember()

这是我收到的错误消息:

PS C:\Users\LENOVO> & C:/Python27/python.exe "c:/Users/LENOVO/OneDrive/Documents/project/python/Selenium/robot olshop.py" Traceback (most recent call last):   File "c:/Users/LENOVO/OneDrive/Documents/project/python/Selenium/robot olshop.py",line 77,in <module>
    OpenProfileMember()   File "c:/Users/LENOVO/OneDrive/Documents/project/python/Selenium/robot olshop.py",line 70,in OpenProfileMember
    x.click()   File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py",line 80,in click
    self._execute(Command.CLICK_ELEMENT)   File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py",line 633,in _execute
    return self._parent.execute(command,params)   File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py",line 321,in execute
    self.error_handler.check_response(response)   File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py",line 242,in check_response
    raise exception_class(message,screen,stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <a class="bn" href="/rxrzimam?fref=gm"> is stale; either the element is no longer attached to the DOM,it is not in the current frame context,or the document has been refreshed
seraph59 回答:如何与硒中的click()循环?

您将获得StaleElementReferenceException,这意味着您要单击的元素不再显示在页面上,或者它的上下文已经以某种方式更改,并且您对该特定元素的列表引用也不再有效。

您可以通过重新定位find列表来修复它。调用x.click()之后,find中的所有元素都已失效,因为您甚至不在该页面上。单击back时,页面上的元素与单击之前的元素不同。

def OpenProfileMember():
    open('https://mbasic.facebook.com/browse/group/members/?id=1600319190185424')

    # get number of elements to click on
    find_length = len(driver.find_elements_by_class_name('bn'))

    # declare a counter to track the loop and keep track of which element in the list to click
    list_count = 0

    # loop through elements and click the element at [list_count] index
    while (list_count < find_length)

        # get the elements
        find = driver.find_elements_by_class_name('bn')

        # click the current indexed element
        find[list_count].click()

        # go back
        time.sleep(3)
        driver.back()

重要的是,while循环的每次迭代都通过调用find来刷新driver.find_elements变量。如果您在进入循环之前找到了元素,然后执行click()back()动作,则将始终遇到StaleElement异常。

我不确定if x != find[0]:应该检查什么。否则,您正在调用continue -我知道,此循环只会单击列表中的第一个元素。这是您的意图,还是您想单击所有元素?

本文链接:https://www.f2er.com/3157257.html

大家都在问