2 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
你可以看看HTML Agility Pack:
然后,您可以從網(wǎng)頁(yè)中找到所有鏈接,例如:
var hrefs = new List<string>();
var hw = new HtmlWeb();
HtmlDocument document = hw.Load(/* your url here */);
foreach(HtmlNode link in document.DocumentNode.SelectNodes("//a[@href]"))
{
HtmlAttribute attribute = link.Attributes["href"];
if (!string.IsNullOrWhiteSpace(attribute.Value))
hrefs.Add(attribute.Value);
}

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
首先,您可以創(chuàng)建一個(gè)函數(shù)來像您所做的那樣返回整個(gè)網(wǎng)站的 HTML 代碼。這是我有的!
public string GetPageContents()
{
string link = "https://www.abc.net.au/news/science/"
string pageContent = "";
WebClient web = new WebClient();
Stream stream;
stream = web.OpenRead(link);
using (StreamReader reader = new StreamReader(stream))
{
pageContent = reader.ReadToEnd();
}
stream.Close();
return pageContents;
}
然后你可以創(chuàng)建一個(gè)函數(shù)來返回一個(gè)子字符串或一個(gè)子字符串列表(這意味著如果你想要所有 < a > 標(biāo)簽,你可能會(huì)得到多個(gè)標(biāo)簽)。
List<string> divTags = GetBetweenTags(pageContents, "<div>", "</div>")
這將為您提供一個(gè)列表,例如,您可以在其中再次搜索每個(gè) < div > 標(biāo)記內(nèi)的 < a > 標(biāo)記。
public List<string> GetBetweenTags(string pageContents, string startTag, string endTag)
{
Regex rx = new Regex(startTag + "(.*?)" + endTag);
MatchCollection col = rx.Matches(value);
List<string> tags = new List<string>();
foreach(Match s in col)
tags.Add(s.ToString());
return tags;
}
編輯:哇不知道 HTML Agility Pack,謝謝@Gauravsa 我會(huì)更新我的項(xiàng)目以使用它!
- 2 回答
- 0 關(guān)注
- 331 瀏覽
添加回答
舉報(bào)