I am new to Selenium and I would like to write a Python script that searches some keywords on google and automatically opens a page when the keywords are found.
I have been trying to work around with the script from this website:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
if __name__ == "__main__":
driver = webdriver.Firefox()
wait = WebDriverWait(driver, 100)
driver.get("http://google.com")
inputElement = driver.find_element_by_name("q")
inputElement.send_keys("Irwin Kwan")
wait.until(EC.element_to_be_clickable((By.XPATH,"//a[@href='http://irwinhkwan.wordpress.com/']")))
blog = driver.find_element_by_xpath("//a[@href='http://irwinhkwan.wordpress.com/']")
blog.click()
driver.quit()
It works perfectly if the xpath is displayed in the page. However, if it is not, we wait forever.
How can I check if an element is there, and if it is there I click on it?
I tried using 'try' as it is given in the documentation, or NoSuchElementException, but I admit being confused with the "double negation ;-):
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()
Ultimately, I would like a while loop that goes to the page number X of the google results and click each time it finds a specific address.
If someone can give me a hand that would be great! I am pretty sure it is trivial, but despite all the documentation available online I haven't been able to work this out for the last couple of days...
except NoSuchElementException: print "Element was not found"before thefinally:line your program will open the page, wait 10 seconds for the element to appear, allowing you to interact with it, or it won't find it within 10 secs, will print out the message. Either way it will close the browser at the end.Try this, if it works do this, else do something else other than blowing up.If you're always seeing the print line, perhaps your selector is incorrect?