Python and selenium: locating elements

Discussion in 'Mac Programming' started by bulldoze, Nov 29, 2014.

  1. bulldoze, Nov 29, 2014
    Last edited: Nov 30, 2014

    bulldoze macrumors regular

    Mar 15, 2011

    I am new to python and selenium webdriver and I am completely flummoxed by locating elements in a web page. For instance, I am trying to input a search term in the search box of the home page of macrumors: the code in the webpage has this section in it:

    <div class="search">
    <span class="icon"></span>
    <form class="search-form" action="">
    <input type="text" class="bginput" name="s" size="20" placeholder="Search

    My python code is this:

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    driver = webdriver.Firefox()
    # Go to Macrumors
    # Select the search box
    python_link = driver.find_element_by_name('s')
    python_link.send_keys('hello world!')
    Does anyone know why this does not work? it opens Firefox and Macrumors but then does nothing and finished. Many thanks!
  2. ArtOfWarfare macrumors G3


    Nov 26, 2007
    You should check what python_link is.

    Better than using find_element_by_name, use find_elements_by_name (note the s, making it plural). How many elements are returned? If it's more than 1, I would imagine your problem is that your code is returning a different element than what you think it is.

    Try using an interactive session of Python instead of just writing a script and running it. It's helpful with introspection and debugging.
  3. kryten2, Nov 29, 2014
    Last edited: Nov 29, 2014

    kryten2 macrumors 6502a

    Mar 17, 2012
    This works for me :

    Note : OS X 10.9.5 - Python 2.7.5 - selenium-2.44.0 - Firefox 25.0.1

    Attached Files:

  4. bulldoze thread starter macrumors regular

    Mar 15, 2011
    I tried the interactive session and it worked fine.

    I then run my script again and I think I just changed the Python_link variable to elem and it worked?!? I don't think I changed anything else.

    Thanks for the help guys.

Share This Page