繁体   English   中英

查找字符串中的所有HTML和非HTML编码的URL

[英]Find all HTML and non-HTML encoded URLs in string

我想在一个字符串中找到所有URL。 我在StackOverflow上发现了各种解决方案,这些解决方案根据字符串的内容而有所不同。

例如,假设我的字符串包含HTML,则此答案建议使用BeautifulSouplxml

另一方面,如果我的字符串仅包含不带HTML标记的纯URL,则此答案建议使用正则表达式。

鉴于我的字符串同时包含HTML编码的URL和纯URL,因此找不到合适的解决方案。 这是一些示例代码:

import lxml.html

example_data = """<a href="http://www.some-random-domain.com/abc123/def.html">Click Me!</a>
http://www.another-random-domain.com/xyz.html"""
dom = lxml.html.fromstring(example_data)
for link in dom.xpath('//a/@href'):
    print "Found Link: ", link

如预期的那样,将导致:

Found Link:  http://www.some-random-domain.com/abc123/def.html

我还尝试了@Yannisp提到的twitter-text-python库,但似乎没有提取两个URL:

>>> from ttp.ttp import Parser
>>> p = Parser()
>>> r = p.parse(example_data)
>>> r.urls
['http://www.another-random-domain.com/xyz.html']

从包含HTML和非HTML编码数据混合的字符串中提取两种URL的最佳方法是什么? 有没有一个好的模块已经做到了? 还是我被迫将regex与BeautifulSoup / lxml结合使用?

我投票是因为它激发了我的好奇心。 似乎有一个名为twitter-text-python的库,该库解析Twitter帖子以检测url和hrefs。 否则,我会使用regex + lxml组合

您可以使用RE查找所有URL:

import re
urls = re.findall("(https?://[\w\/\$\-\_\.\+\!\*\'\(\)]+)", example_data)

它包括字母数字,“ /”和“ URL中允许的字符”

根据@YannisP的回答,我提出了以下解决方案:

import lxml.html  
from ttp.ttp import Parser

def extract_urls(data):
    urls = set()
    # First extract HTML-encoded URLs
    dom = lxml.html.fromstring(data)
    for link in dom.xpath('//a/@href'):
        urls.add(link)
    # Next, extract URLs from plain text
    parser = Parser()
    results = parser.parse(data)
    for url in results.urls:
        urls.add(url)
    return list(urls)

结果是:

>>> example_data
'<a href="http://www.some-random-domain.com/abc123/def.html">Click Me!</a>\nhttp://www.another-random-domain.com/xyz.html'
>>> urls = extract_urls(example_data)
>>> print urls
['http://www.another-random-domain.com/xyz.html', 'http://www.some-random-domain.com/abc123/def.html']

我不确定这在其他URL上的效果如何,但似乎可以满足我的需要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM