使用C#和,我试着
不使用分隔符,因此,如果任何值之间有空格,则不能拆分文本。二、属性、设置和Config是固定的;但是子项的数目和它们的值不固定。所以他们的立场在不断变化。
我应该采取什么方法?
下面给出了一个示例HTML。
<span class="list_props">
<div style="height:8px;overflow:hidden;clear:left;"></div>
<strong>Profile</strong>
<strong style="font-style:italic;">Prop1:</strong>
<a href="" title="P1-Profile Item 1">P1 Profile Item 1</a>
<strong style="font-style:italic;">Prop2:</strong>
<a href="" title="P2-Profile Item 1">P2 Profile Item 1</a>
<strong style="font-style:italic;">Prop3:</strong>
<a href="" title="P3-Profile Item 1">P3 Profile Item 1</a>
<a href="" title="P3-Profile Item 2">P3 Profile Item 2</a>
<div style="height:8px;overflow:hidden;clear:left;"></div>
<strong>Settings</strong>
<strong style="font-style:italic;">Setting1:</strong>
<a href="" title="Setting1 Value1">Setting1 Value1</a>
<div style="height:8px;overflow:hidden;clear:left;"></div>
<strong>Config</strong>
<strong style="font-style:italic;">Config:</strong>
<a href="" title="config-1">config 1</a>
<a href="" title="config-2">config 2</a>
</span>我尝试过一些事情,但我能达到的最好的是下面给出的。它没有给出适当的结果。
var props = c.FindElement(By.XPath("//*[@id='ajax-prop-details-" + objectid + "']"))
.FindElements(By.XPath(".//span[@class='list_props']/")).ToList();
foreach(var ca in props)
{
Console.WriteLine("> " + ca.Text);
var attribs = ca.FindElements(By.XPath(".//following-sibling::")).ToList();
foreach (var atrb in attribs)
{
Console.WriteLine(">> " + atrb.Text);
}
}发布于 2020-06-22 07:42:02
你的XPaths有点差,
.//span[@class='list_props']/应改为.//span[@class='list_props'].//following-sibling::,应改为.//following-sibling::*我建议的是在Chrome的检查元素的查找部分测试您的XPaths。

如果以上提供了更新,您的代码将能够正常运行,如下所示:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Linq;
namespace FindingElements
{
public class ProgramB
{
public static IWebDriver Driver = new ChromeDriver();
private static void Test()
{
var props = Driver.FindElements(By.XPath("//span[@class='list_props']")).ToList();
foreach (var ca in props)
{
Console.WriteLine("> " + ca.Text);
var attribs = ca.FindElements(By.XPath(".//following-sibling::*")).ToList();
foreach (var atrb in attribs)
{
Console.WriteLine(">> " + atrb.Text);
}
}
}
public static void Main(string[] args)
{
Driver.Navigate().GoToUrl("file:///D:/temp/example.html");
Test();
}
}
}说到这一点,首先还是很难实现您的意图,原因是属性标记不是它的子项及其值的实际html父级,而是一个“逻辑”父级。这使得使用XPath (通常用于使用父/子关系来定位元素)进行定位仍然很困难,而不是使用其他元素之前或之后的元素进行定位。我建议您也使用一个look here,它可以帮助实现这种类型的元素定位。
https://stackoverflow.com/questions/62492796
复制相似问题