【问题标题】:SyntaxError: invalid syntax while using find_element_by_xpath using Selenium in PythonSyntaxError:在 Python 中使用 Selenium 使用 find_element_by_xpath 时语法无效
【发布时间】:2019-02-14 07:57:46
【问题描述】:

代码试用:

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")

我收到一个错误:

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

【问题讨论】:

    标签: python selenium selenium-webdriver webdriver syntax-error


    【解决方案1】:

    此错误消息...

    SyntaxError: invalid syntax
    

    ...暗示 xpath 表达式不是有效的 xpath 表达式

    当您使用 双引号"..." 作为 xpath 时,您需要提供 属性值单引号中,即'...'

    所以你需要改变:

    @id="ddlHistorical"
    

    收件人:

    @id='ddlHistorical'
    

    有效的代码行:

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

    将是:

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

    【讨论】:

      【解决方案2】:

      在这种情况下不能使用发送键从下拉框中选择值:

      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);
      		}
      	}
      }

      【讨论】:

        猜你喜欢
        • 2022-01-11
        • 2017-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-11
        • 1970-01-01
        相关资源
        最近更新 更多