You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何正确将从表格获取的ID追加到指定URL中?

Hey there! Let's fix that URL concatenation issue you're facing. The core problem here is two-fold: first, the text variable you're trying to use is trapped inside your for-loop (so it's not accessible outside), and second, you're hardcoding the string "text" instead of referencing the actual ID value you retrieved.

Here's a cleaned-up, working solution:

Step 1: Properly Retrieve and Store the Last ID

Your XPath targets the last ID element in the table, so findElements will only return a single element. We can simplify this by using findElement (singular) instead of dealing with a list, which makes the code cleaner. We'll store the ID in a variable that's accessible when we build the URL.

// Grab the last ID element directly (no need for a list)
WebElement lastIdElement = driver.findElement(By.xpath("(//table[contains(@class,'mat-table')]//tr/td[1])[last()]"));
// Extract the text and store it in a reusable variable
String lastId = lastIdElement.getText();
System.out.println("Get the id:" + lastId);

If you want to keep using findElements (maybe for safety in case the element might not exist), you can do this instead:

List<WebElement> idElements = driver.findElements(By.xpath("(//table[contains(@class,'mat-table')]//tr/td[1])[last()]"));
String lastId = "";
// Only extract text if the list isn't empty
if (!idElements.isEmpty()) {
    lastId = idElements.get(0).getText();
    System.out.println("Get the id:" + lastId);
}

Step 2: Correctly Append the ID to the URL

Now just reference the lastId variable when building your new URL, instead of using the string literal "text":

String confirmationURL = "https://test-websites.net/#/email?type=confirm";
// Use the variable lastId instead of "text"
String newurl = confirmationURL + "&id=" + lastId;

// Navigate to the properly formatted URL
driver.get(newurl);

This will generate the exact URL you're expecting: https://test-websites.net/#/email?type=confirm&id=47474 (or whatever the actual ID value is).

A quick note: If there's a chance the ID element might not exist (leading to a NoSuchElementException), wrap the findElement call in a try-catch block to handle that gracefully.

内容的提问来源于stack exchange,提问作者jay m

火山引擎 最新活动