python selenium keep refreshing until item found (Chromedriver)

我怕爱的太早我们不能终老 提交于 2019-12-12 04:22:12

问题


I am trying to achieve the feature of a Python script using selenium to keep refreshing the current chromepage until, for example, the certain item that makes driver.find_element_by_partial_link_text("Schott") is found.

I was thinking about this:

while not driver.find_element_by_partial_link_text("Schott"):
    driver.refresh
driver.find_element_by_partial_link_text("Schott").click()

However, it seems like the function driver.find_element_by_partial_link_text("Schott") is not the way to match the need. Is there other way I can achieve this please?

BTW, currently I am using driver.get(url) to open the webpage but I am wondering how do i run the script on existing webpage that I already open?


回答1:


Using find_element_... will raise a NoSuchElementExeception if it can't find the element. Since I don't know what site you are running this against, i don't know what the best practice would be. However, if it's simply refreshing the page to check for the element, you could try the following:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

driver.Firefox()  # or whatever webdriver you're using
driver.get(url that you are going to)
while True:
    try:
        driver.find_element_by_partial_link_text("Schott"):
    except NoSuchElementException:
        driver.refresh
    else:
        driver.find_element_by_partial_link_text("Schott").click()
        break


来源:https://stackoverflow.com/questions/42683692/python-selenium-keep-refreshing-until-item-found-chromedriver

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