使用正则表达式在python中提取特定的URL

我已经解析了包含带有beautifulsoup的 javascript的html文档,并设法隔离其中的javascript并将其转换为字符串. javascript看起来像这样:

<script>
    [irrelevant javascript code here]
    sources:[{file:"http://url.com/folder1/v.html",label:"label1"},{file:"http://url.com/folder2/v.html",label:"label2"},{file:"http://url.com/folder3/v.html",label:"label3"}],[irrelevant javascript code here]
</script>

我试图获得一个只有这个源数组中包含的url的数组,看起来像这样:

urls = ['http://url.com/folder1/v.html','http://url.com/folder2/v.html','http://url.com/folder3/v.html']

域名是未知的IP,文件夹是随机名称长度,由小写字母和数字组成,每个文件中有1-5个(通常为3个).所有不变的是,他们以http开头,以.html结尾.

我决定使用正则表达式来处理这个问题(我很陌生),我的代码如下所示:urls = re.findall(r’http:// [^ t] [^ s“]’,document )

[^ t]存在,因为文档中还有其他网址,其域名以t开头.我的问题是,有另一个网址与我提取的网址在同一个域中的jpg,它与其他网址一起被放入urls数组.

例:

urls = ['http://123.45.67.89/asodibfo3ribawoifbadsoifasdf3/v.html'
        'http://123.45.67.89/alwefaoewifiasdof224a/v.html','http://123.45.67.89/baoisdbfai235oubodsfb45/v.html','http://123.45.67.89/i/0123/12345/aoief243oinsdf.jpg']

我怎样才能获取html网址?

解决方法

您可以使用r’“(http.*?)”’来获取文本中的网址:

>>> s="""<script>
...     [irrelevant javascript code here]
...     sources:[{file:"http://url.com/folder1/v.html",...     {file:"http://url.com/folder2/v.html",...     {file:"http://url.com/folder3/v.html",...     [irrelevant javascript code here]
... </script>"""

>>> re.findall(r'"(http.*?)"',s,re.MULTILINE|re.DOTALL)
['http://url.com/folder1/v.html','http://url.com/folder3/v.html']

ans用于提取网址列表中的.html,你可以使用str.endswith:

>>> urls = ['http://123.45.67.89/asodibfo3ribawoifbadsoifasdf3/v.html',...         'http://123.45.67.89/alwefaoewifiasdof224a/v.html',...         'http://123.45.67.89/baoisdbfai235oubodsfb45/v.html',...         'http://123.45.67.89/i/0123/12345/aoief243oinsdf.jpg']
>>> 
>>> [i for i in urls if i.endswith('html')]
['http://123.45.67.89/asodibfo3ribawoifbadsoifasdf3/v.html','http://123.45.67.89/alwefaoewifiasdof224a/v.html','http://123.45.67.89/baoisdbfai235oubodsfb45/v.html']

此外,作为此类任务的另一种通用且灵活的方式,您可以使用fnmatch模块:

>>> from fnmatch import fnmatch
>>> [i for i in urls if fnmatch(i,'*.html')]
['http://123.45.67.89/asodibfo3ribawoifbadsoifasdf3/v.html','http://123.45.67.89/baoisdbfai235oubodsfb45/v.html']

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...