我有2个Dropbox和一个按钮的HTML。



<html>
<body>
<table>
<tr>
	<td>
		<select id="dep1" >
			<option>Info</option>
			<option>Mecanique</option>
		</select>
	</td>

	<td>
		<select id="dep2" >
			<option value="001">Glid</option>
			<option value="002">ASR</option>
			<option value="003">Electronique</option>
		</select>
	</td>
	<td>
		<input id="selection" type="submit" onclick="return check2()" value="Go"></input>
	</td>
</tr>
</table
</body>
</html>





这个想法是,当我在第一个Dropbox中选择Info时,第二个将显示Glid和ASR,然后当我单击按钮时,它将打开另一个选项卡并转到另一个网站。
现在,我尝试去网站并选择第一个下拉框,并将第一个下拉框的所有结果保存在txt文件中

IWebDriver driver;
        string url = "My site";
        driver = new ChromeDriver();
        driver.Navigate().GoToUrl(url);
        new SelectElement(driver.FindElement(By.Id("dep1"))).SelectByText("Info");
        var result = driver.FindElement(By.Id("dep2")).Text;
        File.WriteAllText("result.txt", result);


我的问题是,如何将值添加到文本中并显示为:


  001滑翔002 ASR


对于第二个问题,我还有其他一些这样的HTML代码:



<html>
<body>
<table>
<tr>
<td>
<a href="site1">Glid</a>
</td>
<td>
<a href="site1">ASR</a>
</td>
<td>
<a href="site1">Electronique</a>
</td>
</tr>
</table>
</body>
</html>





所以这是同样的问题,如何在不知道表ID的情况下获取所选选项的href?

最佳答案

您可以遍历表元素:

IList<IWebElement> options = driver.FindElements(By.CssSelector("#dep2 > option")); //get all option tags from the table
IList<IWebElement> hrefs = driver.FindElements(By.TagName("a")); //get all hrefs

foreach (IWebElement option in options)
{
    string value = option.GetAttribute("value");
    string text = option.Text;

    foreach (IWebElement href in hrefs)
    {
        if (href.Text.equals(text))
        {
            // do what you need with the href
        }
    }
}

关于c# - 选择不带ID的表并迭代所有href,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34599959/

10-16 04:14
查看更多