如何在selenium中使用click()进行循环?

2024-09-30 10:34:46 发布

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

我想在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

Tags: inpyremotelibpackagesseleniumlinesite
1条回答
网友
1楼 · 发布于 2024-09-30 10:34:46

您将得到一个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循环的每次迭代都通过调用driver.find_elements刷新find变量。如果在进入循环之前找到元素,然后执行click()back()操作,您将始终遇到StaleElement异常

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

相关问题 更多 >

    热门问题