Issues adding WebDriverWait in a for loop - selenium

无人久伴 提交于 2021-01-29 09:45:13

问题


I have the following code, which runs well:

titles = results.find_elements_by_class_name("docsum-title")
    for title in titles:
        print(title.text)

It prints out a list of titles from the find_elements_by_class_name. The title's are also hrefs which I want to click to. However, once I add click functions on title.text hyperlinks that go to a new page, (code below)

titles = results.find_elements_by_class_name("docsum-title")
    for title in titles:
        print(title.text)
        title_wait = WebDriverWait(driver,10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "docsum-title")))
        element = driver.find_element_by_link_text(title.text)
        element.click()
        print('clicked')
        abstract = WebDriverWait(driver,10).until(
            EC.presence_of_element_located((By.ID,"abstract")))
        print(abstract.text)
        driver.back()

it only runs for the first iteration of the for loop - I'll the abstract.text the first time, but then it throws the error

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

at print(title.text). I thought having the title_wait will make the code wait until the new page loads after driver.back() returns to the original page, but I guess I'm wrong. Would appreciate any help!

For reference, the original link is https://pubmed.ncbi.nlm.nih.gov/?term=obatala%5BAffiliation%5D&sort=, and the page it clicks to is the Bone Marrow Adipocyte paper.


回答1:


Something like this but I don't know the xpath to your element.It should be able to go back and forth finding the next class of docsum-title.

titles = len(results.find_elements_by_class_name("docsum-title")) 
for title in range(1,titles):
    title_wait = WebDriverWait(driver,30).until(EC.presence_of_element_located((By.XPATH,"[class='docsum-title'][" + str(title) + "]")))
    print(title_wait.text)



回答2:


Whenever you are facing the stale element error while performing browser navigation, use below approach.

titles = driver.find_elements_by_class_name("docsum-title")

for i in range(len(titles)):
    titlesTemp = driver.find_elements_by_class_name("docsum-title")
    print(titlesTemp.__getitem__(i).text)
    title_wait = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CLASS_NAME, "docsum-title")))
    element = driver.find_element_by_link_text(titlesTemp.__getitem__(i).text)
    element.click()
    print('clicked')
    abstract = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"abstract")))
    print(abstract.text)
    driver.back()


来源:https://stackoverflow.com/questions/63912435/issues-adding-webdriverwait-in-a-for-loop-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!