简体   繁体   中英

Get text from XPath Element using Selenium WebDriver with JavaScript

I'm trying to use Selenium to get text elements from websites using Node.

As an example, I am using the URL: https://www.ebuyer.com/874785-exdisplay-gigabyte-geforce-rtx-2080-ti-gaming-oc-11gb-graphics-card-ebr2-gv-n208tgaming-oc-11gc and the XPath /html/body/section/div[1]/div[3]/div[1]/div[3]/form/button

I can see in an XPaath selector plugin that it results in "Add to Basket", however the below code logs a blank string. Any idea what I'm doing wrong?

I've tried it with a different element on the page which works, so I'm assuming because its a button?

const selenium = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const chromedriver = require('chromedriver');

chrome.setDefaultService(new chrome.ServiceBuilder(chromedriver.path).build());
const driver = new selenium.Builder()
  .withCapabilities(selenium.Capabilities.chrome())
  .build();

await driver.get(url);
await delay(1000);
const value = await driver.findElement(web.By.xpath(xPath)).getText();
console.log(value)

Use the following xpath to identify the button.

//div[@class='purchase-info']//input[@value='Add to Basket']

Update:

const value = await driver.findElement(web.By.xpath("//div[@class='purchase-info']//input[@value='Add to Basket']")).getAttribute("value");
console.log(value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM