3

我已经在下午阅读了很多处理这个问题的线程,但不幸的是我目前缺少解决方案:(

我尝试抓取这个网站:https ://www.kumon.co.uk/find-a-tutor/

我使用此代码来存储不同商店的每个 url。为此,我必须迭代下一页直到最后一页。

这是我使用的代码:

def get_urls(url) -> list:
    # Get all URLs to the store pages
    options = Options()
    # options.add_argument('--headless')
    path_chromedriver = Path(__file__).parent.parent.joinpath('externals/chromedriver')
    browser = webdriver.Chrome(str(path_chromedriver), chrome_options=options)
    browser.get(url)
    inputElement = browser.find_element_by_id("centre_search")
    inputElement.send_keys('london')
    inputElement.send_keys(Keys.ENTER)
    store_url = []
    links = browser.find_elements_by_link_text('Choose Centre')
    for link in links:
        href = link.get_attribute('href')
        store_url.append(href)
    while browser.find_element_by_xpath("//ul[@class='pagination']//li[last()]/a/small"):
            WebDriverWait(browser, 20).until(
                    EC.element_to_be_clickable((By.XPATH, "//ul[@class='pagination']//li[last()]/a/small"))).click()
            links = browser.find_elements_by_link_text('Choose Centre')
            for link in links:
                href = link.get_attribute('href')
                store_url.append(href)
    return store_url

不幸的是我得到了一个

selenium.common.exceptions.StaleElementReferenceException:消息:过时的元素引用:元素未附加到页面文档

要使用 Try... 除了不是一个好的解决方案,我正在寻找一个强大的解决方案。我应该从 Chrome 切换到 Firefox 吗?

提前谢谢,尼古拉斯。

4

1 回答 1

1

不知道为什么你认为try/except不是好的解决方案,但这正是你需要的:

from selenium.common.exceptions import WebDriverException

def get_urls(url) -> list:
    # Get all URLs to the store pages
    options = Options()
    # options.add_argument('--headless')
    path_chromedriver = Path(__file__).parent.parent.joinpath('externals/chromedriver')
    browser = webdriver.Chrome(str(path_chromedriver), chrome_options=options)
    browser.get(url)
    inputElement = browser.find_element_by_id("centre_search")
    inputElement.send_keys('london')
    inputElement.send_keys(Keys.ENTER)

    links = browser.find_elements_by_link_text('Choose Centre')
    store_url = [link.get_attribute("href") for link in links]

    while True:
        try:
            WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "//li[last()][not(normalize-space(@class))]/a[@data-page]"))).click()
            WebDriverWait(browser, 10).until(EC.staleness_of(links[-1]))
        except WebDriverException:
            break
        links = WebDriverWait(browser, 10).until(EC.visibility_of_all_elements_located((By.LINK_TEXT, 'Choose Centre')))
        store_url.extend([link.get_attribute("href") for link in links])
    return store_url
于 2018-07-12T18:38:43.320 回答