【问题标题】:Regex to scraping link from onclick = Javascript : Newwindow ()正则表达式从 onclick = Javascript 抓取链接:Newwindow ()
【发布时间】:2020-10-14 15:59:45
【问题描述】:

我需要从两种 html 中抓取 https 链接

一个是这样的

          <a href="javascript:void(0)" onclick="javascript:newwindow1('https://hello.com/uploads/order/8c25ce592gfgfgfh99.pdf');">
this is some content  Lorem Ipsum Lorem Ipsum Lorem Ipsum &nbsp; <img src="/img/pdf.jpg" width="15"></a

另一个是这样的

 <a href="javascript:void(0)" onclick="javascript:newwindow1('https://hello.com//webadmin/pdf/order/2018/Aug/hello this is regarding  an older document Ors._2018-08-31 12:09:12.pdf');">
    this is some content  Lorem Ipsum Lorem Ipsum Lorem Ipsum &nbsp; <img src="/img/pdf.jpg" width="15"></a>

两者的区别在于newwindow1中的链接,因为第二个html链接包含很少的空格 并且链接包含stringpdf两次

现在我想从他们两个中提取链接 我正在使用c#

Regex.Match(HtmlString, @"('https[^\s]+.pdf')");

通过这种方式,我可以从第一个 html 中提取链接,但在第二个 html 中,它的提取方式是这样的

https://hello.com//webadmin/pdf/

https 开始,在pdf 停止,但链接尚未完成

除了regex,请告诉我html agility pack是否可以这样做

【问题讨论】:

  • 如果您的属性值总是用单引号分隔,您可以使用[^'] 而不是[^\s]('https[^']+\.pdf')。转义模式中的点以匹配文字点。
  • 感谢@WiktorStribiżew,它肯定会起作用,您能否将其添加为答案

标签: javascript c# regex html-agility-pack


【解决方案1】:

使用 HtmlAgilityPack,您可以解析 HTML DOM 文档,但无法解析 JavaScript 代码。

如果您知道代码始终按照问题中显示的方式格式化,则您只能使用正则表达式,即如果您需要提取的值始终在单引号内。然后,您可以使用匹配除单引号以外的任何字符的[^'] 否定字符类,而不是匹配除空白字符以外的任何字符的[^\s]

var url = Regex.Match(HtmlString, @"'https[^']+\.pdf'");

或者,只获取不带单引号的 URL:

var url = Regex.Match(HtmlString, @"'(https[^']+\.pdf)'")?.Groups[1].Value;

请注意,您应该将模式中字符类之外的点转义以匹配文字点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 2013-08-21
    • 1970-01-01
    相关资源
    最近更新 更多