【问题标题】:A scraping issue on C# scraping project关于 C# 抓取项目的抓取问题
【发布时间】:2020-06-30 18:04:47
【问题描述】:

祝大家有个美好的一天! 我是使用 c# 构建抓取项目的新手。 现在我正在尝试从网站上抓取标签 href 属性的内容。 但还不能得出好的结论! 网页结构如下:

<table class="matches date_matches grouped">
    <thead></thead>
    <tbody>
        <tr id="date_matches-16-53658" class="group-head clickable" stage-value="212">
            <th colspan="5">
            </th>
            <th class="competition-link">
             <a href="/national/south-africa/psl/20192020/regular-season/r53038/"><span>More…</span></a>
            </th>
        </tr>
        <tr id="xxx">
            ...
        </tr>
    </tbody>
</table>

我将抓取 href url-link 字符串的内容(这里:“/national/south-africa/psl/20192020/regular-season/r53038/”)。 这是我的 c# 抓取项目:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
...
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://....");
ReadOnlyCollection<IWebElement> alinks = driver.FindElements(By.XPath("//td[@class='score-time']/a[contains(@href, 'south-africa')]"));

我尝试了其他一些方法来抓取 href 属性的内容。 但仍然没有得到正确的结果。 谢谢你的好建议!!!

【问题讨论】:

    标签: c# selenium web-scraping


    【解决方案1】:

    请尝试此代码,它将对您有所帮助。

    public string FindHref()
    {
         string href = string.Empty;
         List<IWebElement> anchors = driver.FindElements(By.TagName("a")).ToList();
         for (int i = 0; i < anchors.Count; i++)
         {
             href = anchors[i].GetAttribute("href");
         }
         return href;
    }
    

    【讨论】:

      【解决方案2】:

      试试这个

      var linkList = new List<string>();
      var links = Driver.FindElements(By.CssSelector("a"));
      var linkList = linkList.AddRange(links.Select(link => link.GetAttribute("href")));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-16
        • 2021-07-25
        • 1970-01-01
        • 2018-09-22
        • 2018-11-17
        • 1970-01-01
        • 1970-01-01
        • 2020-07-03
        相关资源
        最近更新 更多