使用C#和Selenium,在没有结构化的情况下,如何获取元素及其值
使用C#和Selenium webdriver for chrome,我试图使用C#和Selenium,在没有结构化的情况下,如何获取元素及其值,c#,selenium,C#,Selenium,使用C#和Selenium webdriver for chrome,我试图 属性标记中的每个属性、设置和配置 他们的子项在子项中 他们的价值就是价值 一,。没有使用分隔符,因此如果任何值之间有空格,则无法拆分文本。 二,。属性、设置和配置是固定的;bu子项的编号及其值不是固定的。因此,他们的立场不断变化 我应该采取什么方法 下面给出了一个HTML示例 <span class="list_props"> <div style="hei
<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>
你的XPath有点不对劲
应更改为//span[@class='list\u props']/
//span[@class='list\u props']
应更改为//following sibling::
//following sibling::*
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进行定位变得困难,但仍然是可能的,XPath通常用于使用元素的父/子关系来定位元素,而不是在另一个元素之前或之后的元素。我建议您也采取一些措施,这有助于实现这种类型的元素定位
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();
}
}
}