C# 抓取项目上的抓取问题



祝大家有美好的一天! 我是用 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链接字符串的内容(此处:"/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 属性的内容。 但仍然没有得到正确的结果。 谢谢你的好建议!!

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

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;
}

试试这个

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

最新更新