Error: The XPath expression provided is invalid for use with the scrollIntoView function in Selenium

My task involves utilizing Python to extract data from a website that features a filter pane requiring scrolling. I came across a code snippet that aids in navigating through a list of elements by iterating through a loop.

recentList = driver.find_elements_by_xpath("/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li")
for item in recentList:
    driver.execute_script('arguments[0].scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"})', item)

I already have a for loop integrated into my existing code and now I aim to incorporate an element that requires scrolling as well. Following the logic presented above (simplified loop):

for p in range(1,15):
    item = driver.find_element_by_xpath(str('/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[' + str(p) + ']'))
    driver.execute_script('arguments[0].scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"})', item)

I'm encountering difficulties as the code doesn't seem to work as intended. The error message I received is as follows:

selenium.common.exceptions.InvalidSelectorException: Message: Given xpath expression "/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[1]" is invalid: SyntaxError: The expression is not a legal expression.

If anyone knows how to resolve this issue, your input would be greatly appreciated. The XPath used in the last piece of code is confirmed to be accurate and functional.

I attempted replacing my current loop with "item in recentList" but encountered issues when trying to scroll through pages on the filter.

Answer №1

This particular error message...

selenium.common.exceptions.InvalidSelectorException: Message: The given xpath expression "/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[1]" is considered invalid: SyntaxError: The expression does not meet the requirements.

...suggests that the XPath expression provided was flawed or not legitimate.

The error highlights an additional third bracket opening within the xpath:

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

Resolution

To correct this issue and remove the extra bracket, it is necessary to adjust the xpath expression in this manner:

list = driver.find_element_by_xpath(str('/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[' + str(p) + ']'))

Further Reading

You may find relevant discussions about similar issues at:

  • InvalidSelectorError: Unable to locate an element with the xpath expression
  • Message “org.openqa.selenium.InvalidSelectorException: Unable to locate an element with the XPath expression” using sendKeys
  • Send whatsapp message to contacts using Python but getting an error: InvalidSelectorException: unable to locate an element

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

Having trouble with jQuery modal not adjusting its height properly

I am a jquery modal popup newcomer. I can open the modal when clicking on the hyperlink, but I'm having trouble with the height setting. Despite my attempts and searches online, I couldn't figure it out. When trying to post a question about the & ...

Sending input values through an identifier within a pop-up dialog box

Struggling with my jQuery and Ajax skills, especially when it comes to editing data. The add method works fine, but the edit functionality is giving me trouble. I have a route for editing like /edit/{id}, and whenever I click the button in the modal, it ...

How can the hreflang tag be used correctly in a React application that supports multiple languages?

I have a React application with 3 pages(routes) and I support 2 languages (English and Spanish). Should I insert the following code into the <head></head> section of the public\index.html file like this? <link rel="alternate" ...

Utilizing HTML5 Canvas for Shadow Effects with Gradients

Surprisingly, it seems that the canvas API does not support applying gradients to shadows in the way we expect: var grad = ctx.createLinearGradient(fromX, fromY, toX, toY); grad.addColorStop(0, "red"); grad.addColorStop(1, "blue"); ctx.strokeStyle = gra ...

Comparison of performance between serializing an object to indexedDB and using JSON.stringify

I am curious about the efficiency differences in terms of browser/CPU/memory between using JSON.stringify for serialization versus writing an object to an object store in indexedDB. The context for this question is optimizing the process of writing an obj ...

Tips for creating a breakpoint in Sass specifically for a 414px iPhone screen size

For my latest project, I am utilizing sass and looking to incorporate a sass breakpoint or media query. My goal is to have the code execute only if the screen size is 414px or less. Below is my existing code: @include media-breakpoint-down(sm) { .sub-men ...

Tips for displaying an HTML page using JavaScript

In my project, I am working with an .html file (File X) that needs to immediately open another .html file (File Y) based on a certain value. Could someone provide guidance on the best way to achieve this using JavaScript? Additionally, I would like the pa ...

Tips for efficiently expanding NodeJS while running it through an Apache web server?

Currently, I have Apache Web Server running alongside NodeJS on the same system but on different ports. I am reverse proxying to connect and use them for various purposes. My concern is how to scale this architecture up to accommodate around 10 million u ...

Is there a way to retrieve the disabled drop-down field value after submitting the form?

I'm struggling with a dropdown field that becomes disabled once an item is selected. After submitting the form, the dropdown field loses its value and I'm left with an empty field. Any suggestions on how to keep a value in the dropdown after subm ...

What is the best way to create a layout with two images positioned in the center?

Is it possible to align the two pictures to the center of the page horizontally using only HTML and CSS? I've tried using this code but it doesn't seem to work: #product .container { display: flex; justify-content: space-between; flex-w ...

Tips on choosing an option from the dropdown menu

Let me outline the steps in my situation: I am adding a new group to the list After adding the group, I need to choose it from the left window and transfer it to the right window. I am uncertain about how to perform the selection. Below is the script I ...

I am struggling to send an email using PHP mailer with POST data

i'm facing challenges with integrating phpmailer and ajax. As a beginner in ajax, I still have some gaps in understanding the concept. When I directly run my php mailer script on a page with preset values, I can successfully send out an email. However ...

Using observables rather than promises with async/await

I have a function that returns a promise and utilizes the async/await feature within a loop. async getFilteredGuaranteesByPermissions(): Promise<GuaranteesMetaData[]> { const result = []; for (const guarantees of this.guaranteesMetaData) { ...

When transitioning from the accordion format for mobile to the tab layout for desktop, the tab panel displays an inaccurate title despite the content being accurate

Currently, I am working on developing a navigation system. The objective is to have an accordion-like layout for mobile and tab-based layout for desktop. Although I have implemented this setup, there seems to be an issue: For instance, if "Link #2" tab is ...

How to fully expand the browser window in Firefox using Selenium WebDriver and C#

Here is the code I have for maximizing Chrome: List<String> capabilityValue = new List<string>(); capabilityValue.Add("--start-maximized"); capabilities = DesiredCapabilities.Chrome(); capabilities.SetCapability("chrome.switches", capabilityVa ...

Is it possible to link the _id of a mongodb array to its corresponding clientId in another array?

I am facing a challenge with 2 arrays retrieved from my MongoDB database. The first array is called users and it contains user objects structured like this: [{ email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a1beb ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

Implementing CORS in ReactJs: A Step-by-Step Guide

When working with React.js, I often use this fetchData config: fetchData = () => { fetch("http://localhost:8000/batch_predict", { method: "POST", headers: { 'Accept': 'application/json, text/plain, */*&apo ...

I'm wondering why my .focus() function is causing the cursor to move to the start of my contenteditable div?

I am currently developing a website for writing books, primarily using php. I have implemented a jQuery function that, upon clicking the "New Chapter" button, triggers an AJAX function along with various other JS/jQuery events. One of these events is inten ...

Encountering the "Variable is not defined" error even when the variable has been previously defined. Currently working with EJS and Node

38| <h2 class="card-activity"> 39| <!-- Display Activity --> >> 40| <%= data.activity %> 41| </h2> 42| <div class="card-info"> 43| ...