Using Xpath in Selenium beginner: how to select and click on a link nested within a <ul><li> element

When working with Selenium Basic, I attempted to click on the element 'MyLocalLang' nested within <li> tags. Here is the source:

<div id="navBar" class="NavBar">
<nav id="navMenu" class="Wrapper"> == 40
    <ul class="navMenuUL">
        <li> ... </li>
        <li> ... </li>
        <li> ... </li>
        <li> ... </li>
        <li> ... </li>
        <li> ... </li>
        <li> ... </li>
        <li> ... </li>
        <li> 
            <a class="nav" href="//en.mysite.com/item/">MyLocalLang</a>
        </li>
        <li> ... </li>
    </ul>
</nav>

I need to specifically select the <li> tag that contains the desired link, as the other elements are irrelevant. The code

driver.FindElementByXPath("//*[@id='navMenu']/ul/li[9]/a")
works, but:

  • The target link may not always be in the ninth position;
  • The link text could be in various languages, such as MaLangueLocale, MiaLinguaLocale, MiIdiomaLocal, etc.;
  • The URL could also vary in different languages, like fr.mysite.com, it.mysite.com, en.mysite.com, etc.;
  • The @class 'nav' attribute is present in all <li> tags and is therefore not useful for targeting.

Despite several attempts, I have been unable to accomplish this task. I have tried:

driver.FindElementByXPath("//*[@id='navMenu']/ul/li[contains(@href,'*mysite.com/item/')]/a").Click

with and without the final /a, among other variations.

If anyone can assist me in constructing the correct xpath expression to click on the link regardless of its language or position within the list, please advise. Please note that I am utilizing Selenium in a VBA project.

Thank you in advance.

Answer №1

The href attribute is located within the <a> tag, not the <li> tag. Give this a try:

driver.FindElementByXPath("//*[@id='navMenu']/ul/li/a[contains(@href, 'mysite.com/item/')]").Click()

Make sure to exclude the * from the href value since it will be treated as part of the search string.

Answer №2

href is a attribute of anchor and not for li, therefore you should try:

//li/a[contains(@href,'mysite.com/item/')]

Answer №3

To start, gather all li elements and store them in a list of WebElements. Next, iterate through the list using the tagName of each element within a loop.

Consider employing a css selector similar to the one below:

List<WebElement> allLiElements = driver.findElements(By.cssSelector("#navBar > ul > li"));
for (WebElement element : allLiElements) {
    String link = element.findElement(By.tagName("a")).getAttribute("href");
    if(link.contains("example.com")){
        element.findElement(By.tagName("a")).click();
    }           
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding all anchor tags in raw HTML using htmlagilitypack

My HTML document contains the following code snippet: string htmlData = "<!DOCTYPE html><html><Head></Head><body>&lt;div&gt;&lt;a target=\"_blank\" href=\"http://blender.palmbeachschools.org/GetFile ...

Using Selenium to interact with drop-down lists using div tags instead of select tags

As a newcomer to automated testing using Selenium Web Driver, I am struggling to test drop down lists for the location type without relying on the select command. The element in question is enclosed within a div tag. I attempted sending keys but that meth ...

Using SVG as a background image on Internet Explorer with zoom capabilities

I am having an issue with my SVG used as a background image: <div class="bubble"></div> Here is the CSS I am using: .bubble { background-image: url(https://beta.creasoft.cz/Images/bubble-small.svg); background-repeat: no-repeat; width ...

Shrinking Navigation Menu - Changing Font Color

I'm attempting to update the menu text color when the header shrinks on scroll. I've experimented with this code: $(window).scroll(function() { if ($(document).scrollTop() > 20) { $('ul.art-hmenu>li>a').addClass('s ...

Python Selenium encountered an error message stating, "selenium.common.exceptions.WebDriverException: Message: chrome not reachable" while attempting to access a local

Using Selenium to extract information from a local HTML file named output.html has been my latest challenge. Within the Python interpreter, I can successfully import necessary modules, create a driver object using webdriver.Chrome, and fetch my local file ...

Separating each word of a title onto its own line using HTML and CSS

Looking for a solution to style dynamic titles with each word on its own line? Check out the desired look here. (Note the black backgrounds for each word) The challenge is keeping the same style while having the whole title inside one tag without dynamica ...

I am currently working on a website project where I am looking to access and read a local JSON file using JavaScript

info = {"items": [ { "title": "example 1", "author": "writer 1" }, { "title": "sdample 2", "author": "a ...

Unable to load XML in Chrome using JQuery

Can anyone explain why the code below works in Firefox but not Chrome? I'm currently testing it on my local machine. Thanks for any insights you can provide! <html> <head> <script type="text/javascript" src="jquery.js"> ...

Navigate the conversation within the dialog without affecting the content below

Is it possible to have a dialog with scrollable content on top of a page that is also scrollable, but when trying to scroll inside the dialog using the mouse wheel, only the dialog body scrolls and not the page below it? What approach can be used to accom ...

Is there a way to restrict the number of simultaneous browser requests in Chrome?

Background One thing that I have observed is that almost all proxy providers incorporate the idea of "Maximum threads", which essentially refers to the maximum number of concurrent/parallel browser requests allowed at any given time. With many modern webs ...

What strategies can be employed to incorporate numerous images on my webpage while reducing the number of HTTP requests?

I am working on a website similar to WWW.outgrow.me where each image on the main page requires a server request. Does anyone have suggestions on how to load multiple images at once from the server and display them on the main page, in order to reduce the n ...

What is the best way to include a .AVI file in an HTML document?

I have come across some examples of .AVI in HTML on the internet. However, my page seems to be having issues. It displays fine in Chrome on my computer. But in Internet Explorer, there is a bar at the top and the videos appear blank afterwards. It ...

Issue with image mapping in IE causes incomplete clickability of image mapped areas

Looking for some help with this code snippet I have on my webpage... <a href="http://www.page1.com" ><img usemap="#termsclickable" src="picture.png" /></a> <map id="termsclickable" name="termsclickable"> <area shape="rect" coo ...

Create automatic transcripts for videos, including subtitles and captions

Are there any tools or plugins available that can automatically create a transcript of a video for website playback? For example, generating captions and subtitles in the English language. ...

How can I stop and hover over time in AngularJs Interval?

Within my UI, I have a time element that is continuously updated using AngularJS Interval. Even the milliseconds are constantly running. Is it possible to implement a feature where the time pauses when hovering over it? Any assistance would be greatly appr ...

Error: Unbalanced parentheses detected in the argument list at file path C:UsersgajjaOneDriveDesktopuser_loginviewsupdate.ejs during ejs compilation

When I try to update, instead of showing the form fill field, an error pops up. Can someone assist me with this? <!DOCTYPE html> <html> <head> <title>Form Data</title> </head> <body> <h1>Form Dat ...

Utilizing selenium to interact with JavaScript-generated radio buttons

My Java code includes a set of dynamically generated radio buttons using JavaScript that I am trying to interact with. Despite attempting to use xpath to locate and click on one of the radio buttons, I keep receiving an error message: Exception in thre ...

How to center an item in a Bootstrap navbar without affecting the alignment of other right-aligned items

Currently, I am in the process of designing a website and have implemented a Bootstrap navbar. The navbar consists of three icons aligned to the right, and I am looking to center another element. However, when I use mx-auto, the element does not center per ...

Can you please provide the password needed to enable the "safaridriver" command?

Can you remind me of the password needed for running the command "safaridriver --enable" on my MAC? Whenever I try to execute "safaridriver --enable" in the terminal, my MAC prompts me for a password. I have entered the sudo command's password, but i ...

The jQuery click event is failing to trigger

I am facing an issue with some buttons that have specific classes. Here is an example: https://i.sstatic.net/CVIR2.png Each of these buttons contains JSON data stored in a data attribute. I have created a function to detect when a button is clicked and p ...