如何从html提取一些url ?



我需要从本地html文件中提取所有图像链接。不幸的是,我不能安装bs4cssutils来处理html。

html = """<img src="https://s2.example.com/path/image0.jpg?lastmod=1625296911"><br>
<div><a style="background-image:url(https://s2.example.com/path/image1.jpg?lastmod=1625296911)"</a><a style="background-image:url(https://s2.example.com/path/image2.jpg?lastmod=1625296912)"></a><a style="background-image:url(https://s2.example.com/path/image3.jpg?lastmod=1625296912)"></a></div>"""

我尝试使用正则表达式提取数据:

images = []
for line in html.split('n'):
images.append(re.findall(r'(https://s2.*?lastmod=d+)', line))
print(images)
[['https://s2.example.com/path/image0.jpg?lastmod=1625296911'],
['https://s2.example.com/path/image1.jpg?lastmod=1625296911)"</a><a style="background-image:url(https://s2.example.com/path/image2.jpg?lastmod=1625296912)"></a><a style="background-image:url(https://s2.example.com/path/image3.jpg?lastmod=1625296912']]

我想我的正则表达式是贪婪的,因为我使用.*?如何得到以下结果?

images = ['https://s2.example.com/path/image0.jpg',
'https://s2.example.com/path/image1.jpg',
'https://s2.example.com/path/image2.jpg',
'https://s2.example.com/path/image3.jpg']

如果可以的话,所有链接都用src="..."url(...)括起来

谢谢你的帮助。

import re
indeces_start = sorted(
[m.start()+5 for m in re.finditer("src=", html)]
+ [m.start()+4 for m in re.finditer("url", html)])
indeces_end = [m.end() for m in re.finditer(".jpg", html)]
image_list = []
for start,end in zip(indeces_start,indeces_end):
image_list.append(html[start:end])
print(image_list)
那是我想到的一个解决办法。它包括查找图像路径字符串的开始索引和结束索引。如果有不同的图像类型,显然需要进行调整。

编辑:更改了开始条件,以防文档中有其他url

可以使用

import re
html = """<img src="https://s2.example.com/path/image0.jpg?lastmod=1625296911"><br>
<div><a style="background-image:url(https://s2.example.com/path/image1.jpg?lastmod=1625296911)"</a><a style="background-image:url(https://s2.example.com/path/image2.jpg?lastmod=1625296912)"></a><a style="background-image:url(https://s2.example.com/path/image3.jpg?lastmod=1625296912)"></a></div>"""
images = re.findall(r'https://s2[^s?]*(?=?lastmod=d)', html)
print(images)

参见Python演示。输出:

['https://s2.example.com/path/image0.jpg',
'https://s2.example.com/path/image1.jpg',
'https://s2.example.com/path/image2.jpg', 
'https://s2.example.com/path/image3.jpg']

也请参见regex演示。这意味着

  • https://s2-一些文字
  • [^s?]*- 0个或多个字符(空格和?字符除外)
  • (?=?lastmod=d)-紧接着右边,必须有?lastmode=和一个数字(文本不被添加到匹配中,因为它是一个正向前看的模式,一个非消耗模式)。
import re
xx = '<img src="https://s2.example.com/path/image0.jpg?lastmod=1625296911" alt="asdasd"><img a src="https://s2.example.com/path/image0.jpg?lastmod=1625296911">'
r1 = re.findall(r"<img(?=s|>)[^>]*>",xx)
url = []
for x in r1:
x = re.findall(r"srcs{0,}=s{0,}['"][wd:/.=]{0,}",x)
if(len(x)== 0): continue
x = re.findall(r"http[s]{0,1}[wd:/.=]{0,}",x[0])
if(len(x)== 0): continue
url.append(x[0])
print(url)

最新更新