[英]Selenium C#: How to get the properties/attributes of a class inside another class?
這是一個 HTML 文件的正文
<div class ="pic">
<a class = "img" href = "abcxyz.com">
</a>
<a class = "date" href = "asdfg.com">
<span> Feb 02 </span>
</a>
</div>
這是我的代碼,當我想獲取諸如獲取圖像鏈接之類的信息時
List<IWebElement> imgElements = driver.FindElements(By.ClassName("img")).ToList();
foreach (IWebElement imgElement in imgElements)
{
img_URL = imgElement.GetAttribute("href").;
Console.WriteLine(img_URL);
}
但是現在,我想要的是從“img”類和“date”類中獲取鏈接和信息。 請幫我優化一下。 提前致謝。
由於類img
和date
都在同一個父類pic
,您可以使用公共 xpath 獲取列表中的兩個值,然后遍歷該列表以獲取所需的值。
你可以這樣做:
List<IWebElement> imgElements = driver.FindElements(By.Xpath("//div[@class='pic']//a")).ToList();
foreach (IWebElement imgElement in imgElements)
{
img_URL = imgElement.GetAttribute("href");
Console.WriteLine(imgElement.Text);
Console.WriteLine(img_URL);
}
您可以創建一種用於解析特定標簽的方法,如下所示(我使用它來解析標簽):
public static IWebElement ResolveLabelFromElement(this IWebElement labelValuePairElement)
{
By by = By.TagName("label");
var label = labelValuePairElement.FindElement(by);
return label;
}
並像這樣使用:
var labelElement = element.ResolveLabelFromElement();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.