【问题标题】:How can I extract URLs containing dashes from HTML using R?如何使用 R 从 HTML 中提取包含破折号的 URL?
【发布时间】:2013-08-22 05:59:06
【问题描述】:

我有一些看起来像这样的 HTML:

<ul><li><a href="http://www.website.com/index.aspx" target="_blank">Website</a></li>
<li><a href="http://website.com/index.html" target="_blank">Website</a></li>
<li><a href="http://www.website-with-dashes.org" target="_blank">Website With Dashes</a></li>
<li><a href="http://website2.org/index.htm" target="_blank">Website 2</a></li>
<li><a href="http://www.another-site.com/">Another Site</a></li>

使用

m<-regexpr("http://\\S*/?", links, perl=T)
links<-regmatches(links, m)

获取链接,但其中带有破折号的链接被截断如下:

http://www.website.com/index.aspx
http://website.com/index.html
http://www.website
http://website2.org/index.htm
http://www.another-site.com/

我认为 /S 匹配任何非空格。怎么回事?

【问题讨论】:

  • 我无法复制您的问题。如果我用\" 替换",这样我就可以用readLines 导入文本,一切都会按您的预期进行。

标签: html regex r


【解决方案1】:

使用XML::getHTMLlinks

例如

library(XML)
# assuming your html document is'foo.html')

 getHTMLLinks(doc = 'foo.html')
# [1] "http://www.website.com/index.aspx"  "http://website.com/index.html"      "http://www.website-with-dashes.org"
# [4] "http://website2.org/index.htm"      "http://www.another-site.com/" 

用正则表达式解析HTML 不一定简单。 https://stackoverflow.com/a/1732454/1385941 读起来很有趣。

【讨论】:

  • 是的,我已经读过了,但我只是觉得我的应用程序足够简单,所以我可以试一试。这个答案并没有解决我的确切问题,但它为我指明了解决问题的不同且可能更好的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
相关资源
最近更新 更多