[英]Extracting .zip filenames from given URL using regex in Python
我想从给定的URl中提取.zip文件名。 这是我的代码-
import re
print(re.findall(r'href=[\'"]?([^\'" >]+)','<a href="http://www.example.com/files/world_data1.zip"><b>World Data Part 1</b></a> <br/> <a href="http://www.example.com/files/world_data2.zip"><b>World Data Part 2</b></a>'))
例如:
输入- <a href="http://www.example.com/files/world_data1.zip"><b>World Data Part 1</b></a> <br/> <a href="http://www.example.com/files/world_data2.zip"><b>World Data Part 2</b></a>
预期输出world_data1.zip,world_data2.zip
。
我尝试使用各种格式的.zip $,但出现了一个空列表。 谁能帮我这个?
你可以用
import re
html = """' <a href="http://www.example.com/files/world_data1.zip"><b>World Data Part 1</b></a> <br/> <a href="http://www.example.com/files/world_data2.zip"><b>World Data Part 2</b></a>'"""
rx = re.compile(r"""href=(["'])(.*?)\1""")
links = [filename
for m in rx.finditer(html)
for filename in [m.group(2).split('/')[-1]]
if filename.endswith('.zip')]
print(links)
屈服
['world_data1.zip', 'world_data2.zip']
href
属性,用/
分割,然后检查最后一部分是否以.zip
结尾。
BeautifulSoup
的解析器和一些xpath
查询。
您可以尝试以下方法:
import re
s = ' <a href="http://www.example.com/files/world_data1.zip"><b>World Data Part 1</b></a> <br/> <a href="http://www.example.com/files/world_data2.zip"><b>World Data Part 2</b></a>'
print(re.findall(r'href="[^"]+?/([^/"]+\.zip)"', s))
或者,更严格地,使用以下方式:
import os
from pyquery import PyQuery as pq
doc = pq(s)
a_list = doc('a[href]') # Get all `a` elements that have a `href` attrib.
hrefs = [os.path.basename(a.attrib['href']) for a in a_list]
print(list(filter(lambda x: x.endswith('.zip'), hrefs)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.