问题描述
我需要从 HTML 文档中的所有图像标签中提取 src 元素.
I need to extract the src element from all image tags in an HTML document.
因此,输入是一个 HTML 页面,输出将是一个指向图像的 URL 列表:例如... http://www.google.com/intl/en_ALL/images/logo.gif
So, the input is an HTML page and the output would be a list of URL's pointing to images:ex... http://www.google.com/intl/en_ALL/images/logo.gif
以下是我目前想到的:
<imgs+src=""(http://.*?)
这不适用于 src 不在 img 标签之后的标签,例如:
This does not work for tags where the src isn't directly after the img tag, for example:
<img height="1px" src="spacer.gif">
有人可以帮忙完成这个正则表达式吗?这很容易,但我认为这可能是获得答案的更快方法.
Can someone help complete this regular expression? It's pretty easy, but I thought this may be a faster way to get an answer.
推荐答案
以下正则表达式片段应该可以工作.
The following regexp snippet should work.
<img[^>]+src="([^">]+)"
它查找以 <img
开头的文本,后跟一个或多个不是 >
的字符,然后是 src="
>.然后它会抓取该点和下一个 "
或 >
之间的所有内容.
It looks for text that starts with <img
, followed by one or more characters that are not >
, then src="
. It then grabs everything between that point and the next "
or >
.
但如果可能,请使用真正的 HTML 解析器.它更可靠,可以更好地处理边缘情况.
But if at all possible, use a real HTML parser. It's more solid, and will handle edge cases much better.
这篇关于如何使用正则表达式提取 HTML img 源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!