如何使用 selenium 从 Java 中的 <a href onclick="sometext" 获取 onclick 文本
How do I get the onclick text from <a href onclick="sometext" in Java using selenium
HTML 代码如下所示:
<a href="" onclick="MSV_hybrid_lab_open("construct.asp?pid=DEMO&mode=EnterLab&regn=10887898&pcd=12367&type=L&corpaccd=DEMOLLAB");return false;"><font class="snormal">Planning</font></a>
我需要从 onclick 获取文本。我需要 pid=DEMO
有人可以帮助我吗?我正在使用 java + 硒。谢谢
通过文本查找link,然后得到它的属性onclick
,再解析得到pid
:
// Initialize driver, navigate to the page
WebDriver driver = new FirefoxDriver(); // or other browser
// ... (navigate to the page, etc.)
// Find the link by partial link text
WebElement link = driver.findElement(By.partialLinkText("Planning"));
// Get the attribute (entire value)
String onclick = link.getAttribute("onclick");
// From here you can use any of the string parsing to get what you want.
// Here's the simple regex way:
String pid = "";
Pattern pattern = Pattern.compile("pid=([^\&]*)&"); //search for anything between 'pid=' and '&'
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
pid = matcher.group(1); // should be only one
}
System.out.println(pid);
将打印
DEMO
HTML 代码如下所示:
<a href="" onclick="MSV_hybrid_lab_open("construct.asp?pid=DEMO&mode=EnterLab&regn=10887898&pcd=12367&type=L&corpaccd=DEMOLLAB");return false;"><font class="snormal">Planning</font></a>
我需要从 onclick 获取文本。我需要 pid=DEMO
有人可以帮助我吗?我正在使用 java + 硒。谢谢
通过文本查找link,然后得到它的属性onclick
,再解析得到pid
:
// Initialize driver, navigate to the page
WebDriver driver = new FirefoxDriver(); // or other browser
// ... (navigate to the page, etc.)
// Find the link by partial link text
WebElement link = driver.findElement(By.partialLinkText("Planning"));
// Get the attribute (entire value)
String onclick = link.getAttribute("onclick");
// From here you can use any of the string parsing to get what you want.
// Here's the simple regex way:
String pid = "";
Pattern pattern = Pattern.compile("pid=([^\&]*)&"); //search for anything between 'pid=' and '&'
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
pid = matcher.group(1); // should be only one
}
System.out.println(pid);
将打印
DEMO