首页 > 解决方案 > 在循环中获取元素的 Selenuim Python 问题

问题描述

soup = BeautifulSoup(browser.page_source, "html.parser")
for h1 in soup.find_all('h2'):
    try:
        array.append("https://www.chamberofcommerce.com" + h1.find("a")['href'])
        print("https://www.chamberofcommerce.com" + h1.find("a")['href'])
    except:
        pass

input=browser.find_element_by_xpath('//a[@class="next"]')
while input:
    input.click()
    time.sleep(10)
    soup = BeautifulSoup(browser.page_source, "html.parser")

    for h1 in soup.find_all('h2'):
        try:
            array.append("https://www.chamberofcommerce.com" + h1.find("a")['href'])
            print("https://www.chamberofcommerce.com" + h1.find("a")['href'])
        except:
            pass

这部分代码在yellopages上删除了列表的url,代码运行良好,直到我过去只从搜索的第一页删除url,现在我希望它点击下一步按钮,直到搜索页面完成,敌人示例如果有 20 页的搜索,那么 selenuim 机器人应该点击下一步按钮并删除 url,直到它到达第 20 页,

请查看代码的逻辑,并且在机器人到达第 2 页后我收到以下错误,因为实际页数为 15,并且它在第 2 页崩溃:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

标签: python-3.xseleniumbeautifulsoup

解决方案


while input不是您需要的...请注意,单击“下一步”按钮后,将加载新页面,并且上一页中的所有 WebElement 都不再有效:您必须在每个页面上重新定义它们。尝试以下方法:

while True:
    try:
        browser.find_element_by_xpath('//a[@class="next"]').click()
    except:
        break

使用上面的代码,您应该能够在每个页面可用时单击“下一步”按钮。您可能还需要应用ExplicitWait来等待 Next 按钮可点击:

wait.until(EC.element_to_be_clickable((By.XPATH, '//a[@class="next"]'))).click()

推荐阅读