[英]Search for specific text in html response (ASP.NET Core)
我需要在我們頁面的 html 中搜索特定單詞。
我嘗試使用 c# (asp.net core) 來做到這一點
我的觀點是通過 js 從 View 中獲取 url 和 word 進行搜索,如果單詞存在則作為響應顯示它,如果不存在,則顯示 smth
我制作了獲取頁面html代碼的方法。 這是代碼
[HttpPost]
public JsonResult SearchWord([FromBody] RequestModel model){
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(model.adress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);
}
else
{
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
}
string data = readStream.ReadToEnd();
string strRegex = model.word;
response.Close();
readStream.Close();
return Json(data);
}
但是,我需要如何正確搜索單詞?
您將無法使用簡單的模式匹配做很多事情,請查看這個非常經典的 - RegEx match open tags except XHTML self-contained tags 。 如果你想做一些嚴肅的抓取,可以考慮使用一些網頁抓取庫,比如html-agility-pack 。 如果您只想搜索網頁中的單個單詞,無論是標記還是 CDATA 等,只需將所有字符連接到一個數組中並使用 string.Contains 或 Regex。
要添加到上一個答案,您可以使用Regex.Match 。 就像是:
string pattern = @"(\w+)\s+(strRegex)";
// Instantiate the regular expression object.
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
// Match the regular expression pattern against your html data.
Match m = r.Match(data);
if (m.Success) {
//Add your logic here
}
注意:您可以做很多事情來優化您的代碼,特別是查看您如何處理流閱讀器。 我會分塊閱讀並嘗試匹配塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.