[英]How to remove string between two words
我使用下面的代碼行下載網頁,
WebRequest request = WebRequest.Create(strURL);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
然后從這里我提取身體部分如下:
int nBodyStart = downloadString.IndexOf("<body");
int nBodyEnd = downloadString.LastIndexOf("</body>");
String strBody = downloadString.Substring(nBodyStart, (nBodyEnd - nBodyStart + 7));
現在我想刪除身體部分附帶的任何javascript,我該怎么做?
我的目標是獲取網頁的唯一內容。 但由於每個頁面可能有不同的方法,所以我試圖刪除任何js標簽,然后使用以下RegEx刪除任何HTML標簽
Regex.Replace(strBody, @"<[^>]+>| ", "").Trim();
但我不知道如何刪除腳本標簽之間的js,因為腳本可能是多行或單行。
提前致謝。
你可以使用HtmlAgilityPack
WebRequest request = WebRequest.Create(strURL);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(html);
// to remove all tags
var result = document.DocumentNode.InnerText;
// to remove script tags inside body
document.DocumentNode.SelectSingleNode("//body").Descendants()
.Where(n => n.Name == "script")
.ToList()
.ForEach(n => n.Remove());
要匹配腳本標記(包括對的內部),請使用以下命令:
<script[^>]*>(.*?)</script>
要匹配所有HTML標記(但不匹配內部),您可以使用:
</?[az][a-z0-9]*[^<>]*>
我剛才意識到你可能也想刪除樣式標簽:
<style[^>]*>(.*?)</style>
完整的正則表達式字符串:
<script[^>]*>(.*?)</script>|<style[^>]*>(.*?)</style>|</?[az][a-z0-9]*[^<>]*>|<[^>]+>|
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.