gpt4 book ai didi

c# - Selenium webdriver 系统无效转换异常

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:33 24 4
gpt4 key购买 nike

为了在 C# 中为神经网络收集一些测试数据,我想使用 Selenium 来抓取一些动态生成的数据 WSJ . Selenium 站点上有一个示例实现似乎完全符合我的需要 Finding all the input elements to the every label on a page .该示例在 TagName 上搜索,我在 ClassName 上搜索,但除此之外,我认为它们是相同的。然而,当我运行这段代码时,使用 IWebElements 创建一个 IList 是可行的,但是下面的 IJavaScriptExecutor 会抛出一个 Invalid Cast 异常:

Unable to cast object of type System.Collections.ObjectModel.ReadOnlyCollection 1[System.Object] to type System.Collections.Generic.IList 1[OpenQA.Selenium.IWebElement]

这是一些代码,这是针对“text”的,我对“num”也这样做:

    // Find elements by class name
IList<IWebElement> labels = driver.FindElements(By.ClassName("text"));

// get all input elements for every class label
IList<IWebElement> labVals = (IList<IWebElement>)((IJavaScriptExecutor)driver).ExecuteScript(
"var labels = arguments[0], labVals = []; for (var i=0; i < labels.length; i++){" +
"labVals.push(document.getElementById(labels[i].getAttribute('for'))); } return labVals;", labels);

我看过这个问题Selenium Web Driver C# InvalidCastException这可能指向相同的问题,但我看不出所提供的答案对我有何帮助。

一个选项可能是将 IJavaScriptExecutor 语句分解为“离散”代码,但我不知道该怎么做。

一旦我在 List 结构中有了文本标签和数据值,我应该能够找到我需要的数字。

最佳答案

这不是使用 javascript,但它会起作用。我会使用 CssSelector 方法来接收您需要的列/行的直通参数,然后您将使用循环调用此方法以从页面获取所有信息。

检查页面的 css 这是我从第一列/行中得到的

table.mdcTable > tbody > tr:nth-of-type(3) > td:nth-of-type(1)

因此,数字“3”与第一行相关,“1”与第一列相关。所以我们可以制作一个方法来返回您想要的确切元素:

public IWebElement test(int line, int row)
{
return driver.FindElement(By.CssSelector(string.Format("table.mdcTable > tbody > tr:nth-of-type({}) > td:nth-of-type({})", line + 2, row)));
}

调用此方法将返回包含文本的元素,因此您需要做的就是使用“element.Text”作为“cell”的值,或者让该方法直接返回文本。

public String test(int line, int row)
{
return driver.FindElement(By.CssSelector(string.Format("table.mdcTable > tbody > tr:nth-of-type({}) > td:nth-of-type({})", line + 2, row))).Text;
}

唯一的问题是“最新”列,因为它们不仅包含数字,还包含一个条。您必须创建一种方法来仅处理这些列。

这最终会是这样的:

            try
{
int line = 1;
int column = 1;
while(column <= 7)
valueOfTheCell = test(line, column);
getLatestGreen(line); //string.Format("tbody > tr:nth-of-type({0}) > td:nth-of-type(9) > span.text", line)
getLatestRed(line); //string.Format("tbody > tr:nth-of-type({0}) > td:nth-of-type(8) > span.text > b", line)
}
catch (NoSuchElementException)
{
//Exception will be thrown when the code reaches the end of the list
}

我不会说这是最佳选择,但它是一种选择。如果您想这样做,我可以帮助您解决有关如何使用选择器的任何问题。

关于c# - Selenium webdriver 系统无效转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30426822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com