简体   繁体   English

Selenium C#-无法找到元素

[英]Selenium C# - Unable to find element

At first I created a code in Selenium IDE firefox addon which is scraping a data from website. 首先,我在Selenium IDE firefox插件中创建了一个代码,该代码正在从网站上抓取数据。 Of course it is working properly in IDE. 当然,它在IDE中可以正常工作。

I want to scrape url from this: 我想从中抓取网址:

<div class="gs-per-result-labels" url="http://example.com/foo/bar"></div>

As HTML is is shown as: 如HTML所示:

<tr>
    <td>open</td>
    <td>http://example.com</td>
    <td></td>
</tr>

<tr>
    <td>storeAttribute</td>
    <td>//div[@class='gs-per-result-labels']@url</td>
    <td>myValue</td>
</tr>

<tr>
    <td>echo</td>
    <td>${myValue}</td>
    <td></td>
 </tr>

Both command are executing properly and echo is giving right value. 两条命令都正确执行, echo给出正确的值。 Next I changed format to C# / NUnit / WebDriver and I copied code to Visual Studio 2015. I added FirefoxDriver and IWebDriver references. 接下来,我将格式更改为C# / NUnit / WebDriver并将代码复制到Visual Studio2015。添加了FirefoxDriverIWebDriver引用。 That is the code: 那是代码:

private static IWebDriver driver;
static void Main(string[] args)
{
    driver = new FirefoxDriver();

    driver.Navigate().GoToUrl("http://example.com");
    Thread.Sleep(10000);
    string myValue = driver.FindElement(By.XPath("//div[@class='gs-per-result-labels']")).GetAttribute("url");
}

I also added Sleep to be sure that the page is fully loaded when it comes to scraping value. 我还添加了“ Sleep ,以确保在抓取值时页面已完全加载。 The thing is I am getting error on FindElement function, because driver was unable to find element. 问题是我在FindElement函数上遇到错误,因为driver无法找到元素。 I am wondering why does that happen. 我想知道为什么会这样。 Everything seems to be the same. 一切似乎都一样。 Do you have any tips? 你有什么建议吗?

I think it is worth to said: The content which I want to scrape is generated by php or javascript (thats are google search result on "example" page which is not google) 我认为值得一提:我要抓取的内容是由php或javascript生成的(那是Google在“示例”页面上的搜索结果,而不是Google)

Best approach would be to check if the Xpath is absolutely correct. 最好的方法是检查Xpath是否绝对正确。 You can always use Firebug or if you want to do it programmatically, below lines should help 您始终可以使用Firebug,或者如果您想以编程方式使用Firebug,则以下几行应该会有所帮助

 List<WebElement> existList=driver.FindElement(By.XPath("//div[@class='gs-per-result-labels']"));
 if(existList.size()>0){
    //SOPL("element present");
 }

I would suggest you to use explicit wait 我建议您使用显式等待

 WebDriverWait wait=new WebDriverWait (driver,60);
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.XPath("//div[@class='gs-per-result-labels']")));
  string myValue = driver.FindElement(By.XPath("//div[@class='gs-per-result-labels']")).GetAttribute("url");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM