使用正则表达式在python中提取特定的URL
发布时间:2020-12-14 05:57:10 所属栏目:百科 来源:网络整理
导读:我已经解析了包含带有beautifulsoup的 javascript的html文档,并设法隔离其中的javascript并将其转换为字符串. javascript看起来像这样: script [irrelevant javascript code here] sources:[{file:"http://url.com/folder1/v.html",label:"label1"},{file:"
我已经解析了包含带有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'] 此外,作为此类任务的另一种通用且灵活的方式,您可以使用 >>> 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'] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |