如何获取<a href="" onclick="sometext" in="" java="" using="" selenium=""

时间:2016-05-14 23:07:52

标签: java selenium testng

="" The HTML code looks like this:

<a href="" onclick="MSV_hybrid_lab_open(&quot;construct.asp?pid=DEMO&amp;mode=EnterLab&amp;regn=10887898&amp;pcd=12367&amp;type=L&amp;corpaccd=DEMOLLAB&quot;);return false;"><font class="snormal">Planning</font></a>

I need to get the text from onclick. I need pid=DEMO

Can someone help me? I am using java + selenium. Thanks

1 个答案:

答案 0 :(得分:0)

按文字查找链接,然后获取其属性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