Executing a script in selenium python

11,215

Find the element with selenium and pass it to execute_script() to click:

link = browser.find_element_by_xpath('//div[@class="vbseo_liked"]/a[contains(@onclick, "return vbseoui.others_click(this)")]')
browser.execute_script('arguments[0].click();', link)

Since I know the context of the problem, here is the set of things for you to do to solve it:

  • click on the "11 others" link via javascript relying on the solution provided here: How to simulate a click with JavaScript?
  • make a custom expected condition to wait for the element text not to ends with "11 others like this." text (this is a solution to the problem you had at Expected conditions with selenium):

    class wait_for_text_not_to_end_with(object):
        def __init__(self, locator, text):
            self.locator = locator
            self.text = text
    
        def __call__(self, driver):
            try :
                element_text = EC._find_element(driver, self.locator).text.strip()
                return not element_text.endswith(self.text)
            except StaleElementReferenceException:
                return False
    

Implementation:

from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class wait_for_text_not_to_end_with(object):
    def __init__(self, locator, text):
        self.locator = locator
        self.text = text

    def __call__(self, driver):
        try :
            element_text = EC._find_element(driver, self.locator).text.strip()
            return not element_text.endswith(self.text)
        except StaleElementReferenceException:
            return False


browser = webdriver.PhantomJS()
browser.maximize_window()
browser.get("http://www.jamiiforums.com/kenyan-news/225589-kenyan-and-tanzanian-surburbs.html")

username = browser.find_element_by_id("navbar_username")
password = browser.find_element_by_name("vb_login_password_hint")

username.send_keys("MarioP")
password.send_keys("codeswitching")

browser.find_element_by_class_name("loginbutton").click()

wait = WebDriverWait(browser, 30)
wait.until(EC.visibility_of_element_located((By.XPATH, '//h2[contains(., "Redirecting")]')))
wait.until(EC.title_contains('Kenyan & Tanzanian'))
wait.until(EC.visibility_of_element_located((By.ID, 'postlist')))

# click "11 others" link
link = browser.find_element_by_xpath('//div[@class="vbseo_liked"]/a[contains(@onclick, "return vbseoui.others_click(this)")]')
link.click()
browser.execute_script("""
function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}

eventFire(arguments[0], "click");
""", link)

# wait for the "div" not to end with "11 others link this."
wait.until(wait_for_text_not_to_end_with((By.CLASS_NAME, 'vbseo_liked'), "11 others like this."))

print 'success!!'
browser.close()
Share:
11,215
user3078335
Author by

user3078335

Updated on June 04, 2022

Comments

  • user3078335
    user3078335 almost 2 years

    I am trying to execute this script in selenium.

    <div class="vbseo_liked">
    <a href="http://www.jamiiforums.com/member.php?u=8355" rel="nofollow">Nyaralego</a>
    ,
    <a href="http://www.jamiiforums.com/member.php?u=8870" rel="nofollow">Sikonge</a>
    ,
    <a href="http://www.jamiiforums.com/member.php?u=8979" rel="nofollow">Ab-Titchaz</a>
    and
    <a onclick="return vbseoui.others_click(this)" href="http://www.jamiiforums.com/kenyan-news/225589-kenyan-and-tanzanian-surburbs.html#">11 others</a>
    like this.
    </div>
    

    This is my code to execute it.

    browser.execute_script("document.getElement(By.xpath(\"//div[@class='vbseo_liked']/a[contains(@onclick, 'return vbseoui.others_click(this)')]\").click()")
    

    It didn't work. What am i doing wrong?

  • user3078335
    user3078335 about 9 years
    selenium.common.exceptions.WebDriverException: Message: {"errorMessage":"'undefined' is not a function (evaluating 'arguments[0].click()')",
  • user3078335
    user3078335 about 9 years
    That was the error message it gave me. Not sure what the reason is.
  • user3078335
    user3078335 about 9 years
    File "sele.py", line 55, in <module> wait.until(wait_for_text_not_to_end_with((By.CLASS_NAME, 'vbseo_liked'), "11 others like this.")) File "/Library/Python/2.7/site-packages/selenium/webdriver/suppor‌​t/wait.py", line 75, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:
  • alecxe
    alecxe about 9 years
    @user3078335 increase the timeout, e.g. 50 instead of 30. The solution worked for me.
  • user3078335
    user3078335 about 9 years
    i got this error. I feel like I owe you a beer. Thank you so much for all your efforts!
  • alecxe
    alecxe about 9 years
    @user3078335 oh, wait a minute. I think I've reproduced your latest problem, let me see.
  • alecxe
    alecxe about 9 years
    @user3078335 funny thing. When we do two types of clicks - via selenium and via js - it works for me. Check it out, updated.
  • oldboy
    oldboy over 2 years
    any idea how to capture the return value of a browser prompt (ideally in python)?