Find and click an item from 'onclick' partial value

后端 未结 3 2084
清歌不尽
清歌不尽 2020-12-19 06:38

Is it possible to click an element through selenium by a partial value of an onclick element?

There are multiple input items on a page, and I only need

相关标签:
3条回答
  • 2020-12-19 07:19

    You are on the right track!

    buttons = driver.find_elements_by_name('booksubmit')
    for button in buttons:
    

    Yes, this exactly. You want to iterate through name = booksubmit elements and check the "onclick" attribute of each one. Here's what the rest would look like:

    buttons = driver.find_elements_by_name('booksubmit')
    for button in buttons:
        onclick_text = button.get_attribute('onclick')
        if onclick_text and re.search('Bedroom Deluxe', onclick_text):
            print "found it!"
            button.click()
    

    BeautifulSoup does not help much in this case, since you still need to use selenium's methods to get ahold of the element to click on.

    0 讨论(0)
  • 2020-12-19 07:27

    Either XPath or CssSelector would do. No need to have any looping, but straightforward locators.

    driver.find_element_by_xpath(".//input[contains(@onclick, '1 Bedroom Deluxe')]")
    
    driver.find_element_by_css_selector("input[onclick*='1 Bedroom Deluxe']")
    
    0 讨论(0)
  • 2020-12-19 07:28

    A general answer for solving these kinds of problems is using the Selenium IDE. From here, you can manually click buttons on a website and have the Selenium IDE (a Firefox plugin) record your actions. From there you can File > Export Test Case As... and choose whatever coding language you want.

    Selenium Downloads page: http://docs.seleniumhq.org/download/

    Selenium IDE Firefox plugin version 2.9.0 http://release.seleniumhq.org/selenium-ide/2.9.0/selenium-ide-2.9.0.xpi

    EDIT: Sometimes you might actually be finding the correct element, but the webdriver tries to find it before it's there. Try adding this line after you create your webdriver:
    In Python:
    driver.implicitly_wait(10)

    This tells your webdriver to give itself more time to try to find the object. It does not add a 10 second wait, but says keep looking for 10 seconds. If it finds the element before 10 seconds, it will continue on as normal.

    0 讨论(0)
提交回复
热议问题