Search code examples
pythonseleniumsubmenu

Issue in selecting sub-menu href using Selenium with Python


The objective is request Selenium to direct to a new page with an address that located under the sub-menu. According to the suggestion from OP1 and OP2, this activity can be achieved as follow;

sub_item_drop= WebDriverWait( self.browser, 20 ).until( EC.presence_of_element_located(
    (By.CSS_SELECTOR, "//a[href='/pguna/ambilduit/permainan.aspx’]") ) )
sub_item_drop.click()

Instead of redirecting to a new url, the compiler instead throw an error;

selenium.common.exceptions.TimeoutException: Message:

It seems to me that the compiler was unable to locate the CSS path given. May I know where did I do wrong? appreciate for any insight.

For easy troubleshooting, the complete outer HTML framework of the website is given below

<li id="tcl_SiringMenu1_sbmenu" class="has-sub">
    <a href="javascript:;">
     <b class="caret pull-right"></b>
     <i class=" tcl tcl -fw tcl -myr"></i>
     <span>Ruang PeluangGame <span class="badge pull-right bg-yellow m-l-4 m-r-4">90000</span> </span>
    </a>

    <ul class="sub-menu" style="display: none;">
        <li id="tcl_SiringMenu1_AmbilDuit">
        <a href="/pguna/ambilduit/permainan.aspx">
        Permainx LODR<span class="badge pull-right bg-green m-l-5 m-r-5">90000</span></a>
        </li>
    </ul>
</li>

Additional info

The full Xpath to the class="sub-menu"

/html/body/form/div[3]/div[2]/div/div[2]/div[2]/div[1]/ul[2]/li[5]/ul

The full Xpath to the class badge pull-right bg-green m-l-5 m-r-5 is

/html/body/form/div[3]/div[2]/div/div[2]/div[2]/div[1]/ul[2]/li[5]/ul/li/a/span

p.s., I am aware several technique using mouse hovering (e.g., OP3, OP4, OP5, OP6) to achieve similar objective, but the technique proposed in OP1 and OP2 look more compact and neat.


Solution

  • Updated Solution:

    Solution 1:

    sub_item_drop= WebDriverWait(self.browser, 20 ).until( 
    EC.element_to_be_clickable(
        (By.XPATH, "//a[@href='/pguna/ambilduit/permainan.aspx']") ) )
    self.browser.execute_script("arguments[0].click();", sub_item_drop)
    

    Solution 2:

        element = wait.until(EC.element_to_be_clickable((By.XPATH, "//li[@id='tcl_SiringMenu1_sbmenu']//ul[@class='sub-menu']//a[@href='/pguna/ambilduit/permainan.aspx']")))
        self.browser.execute_script("arguments[0].click();", element)
    

    Note : please add below imports to your solution

    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.action_chains import ActionChains