【问题标题】:How to extract data from the HTML of the website through PhantomJS Driver如何通过 PhantomJS Driver 从网站的 HTML 中提取数据
【发布时间】:2018-07-13 05:21:19
【问题描述】:

我正在尝试使用 .Net、Selenium、PhantomJs 解析以下网页 https://shop.sprouts.com/shop/flyer。我在元素文本中看到的数据与我在屏幕上看到的完全不同。有没有更好的方法来解析网页?

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.PhantomJS;
[TestClass]
  public class UnitTest1
  {
    const string PhantomDirectory = @"..\..\..\packages\PhantomJS.2.1.1\tools\phantomjs";

[TestMethod]
    public void GetSproutsWeeklyAdDetails()
    {
      using (IWebDriver phantomDriver = new PhantomJSDriver(PhantomDirectory))
      {
        phantomDriver.Navigate().GoToUrl("https://shop.sprouts.com/shop/flyer");
        var elements = phantomDriver.FindElements(By.ClassName("cell-title-text"));
      }
    }
}

【问题讨论】:

  • 改用 chromedriver。它已经支持无头模式。
  • 感谢@baudan 的意见。我会试试看。

标签: .net selenium selenium-webdriver phantomjs headless


【解决方案1】:

根据 WebSite https://shop.sprouts.com/shop/flyer 解析您在元素文本中看到的数据,您需要诱导 WebDriverWait 以使所有所需的元素,您可以使用以下解决方案:

  • 解决方案:

    IList<IWebElement> elements = new WebDriverWait(driver, TimeSpan.FromSeconds(3)).Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.XPath("//span[@class='cell-title-text' and @ng-bind-html='productTitle()']")));
    foreach (IWebElement element in elements)
    {
        Console.WriteLine(element.GetAttribute("innerHTML"));
    }
    
  • 等效的 Python 示例:

    driver.get('https://shop.sprouts.com/shop/flyer')
    myList = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//span[@class='cell-title-text' and @ng-bind-html='productTitle()']")))
    for item in myList:
        print(item.text)
    
  • 控制台输出:

    Sweet Corn, 1 EA
    Cantaloupe Melons, 1 LB
    Red Cherries
    Half Chicken Breast
    Roma Tomatoes
    100% Grass Fed Ground Beef Value Pack
    Colby Jack Rbst Free
    Walnut Halves & Pieces
    

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 2013-03-05
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 2022-01-23
    • 2019-01-05
    相关资源
    最近更新 更多