Shahnawaz Khan
Shahnawaz Khan

Reputation: 73

SyntaxError: invalid syntax while using find_element_by_xpath using Selenium in Python

Code Trials:

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.niftyindices.com/reports/historical-data")
driver.maximize_window()
driver.find_element_by_xpath("//*[@id="ddlHistorical"]").send_keys("NIFTY 100")

I am getting an error:

File "<ipython-input-32-592f058980cd>", line 5
    driver.find_element_by_xpath("//*[@id="ddlHistorical"]").send_keys("NIFTY 100")
                                                       ^
SyntaxError: invalid syntax

Upvotes: 2

Views: 3923

Answers (2)

Bhavesh Soni
Bhavesh Soni

Reputation: 198

Send Keys can not be used in this case to select the value from drop down box:

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class Testing {
	public static WebDriver driver;

	@Test
	public void test() throws InterruptedException {
		System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver");
		driver = new ChromeDriver();
		driver.get("http://www.niftyindices.com/reports/historical-data");
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
		driver.findElement(By.xpath("//*[@id=\"HistoricalData\"]/div[1]/div/div/a")).click();
		Thread.sleep(2000);
		List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"mCSB_2_container\"]/li"));
		for (WebElement element : elements) {
			String mCSB = element.getText();
			
			if (mCSB.equalsIgnoreCase("NIFTY 100"))
			{
				element.click();
			}
			System.out.println(mCSB);
		}
	}
}

Upvotes: 2

undetected Selenium
undetected Selenium

Reputation: 193338

This error message...

SyntaxError: invalid syntax

...implies that the xpath expression was not a valid xpath expression.

As you are using double quotes i.e. "..." for the xpath you need to provide the attribute values within single quotes i.e. '...'.

So you need to change:

@id="ddlHistorical"

To:

@id='ddlHistorical'

Effectively the line of code:

driver.find_element_by_xpath("//*[@id="ddlHistorical"]").send_keys("NIFTY 100")

will be:

driver.find_element_by_xpath("//*[@id='ddlHistorical']").send_keys("NIFTY 100")

Upvotes: 3

Related Questions