换句话说,可以使用 /<tag[^>]*>.*?<\/tag>/
匹配 tag
的正则表达式不包含嵌套的 html 元素 tag
元素?
例如(lt.html):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>greater than sign in attribute value</title>
</head>
<body>
<div>1</div>
<div title=">">2</div>
</body>
</html>
正则表达式:
$ perl -nE"say $1 if m~<div[^>]*>(.*?)</div>~" lt.html
和屏幕抓取:
#!/usr/bin/env python
import sys
import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(sys.stdin)
for div in soup.findAll('div'):
print div.string
$ python lt.py <lt.html
两者都给出相同的输出:
1
">2
预期输出:
1
2
w3c说:
Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.
最佳答案
是的,它是允许的(W3C Validator 接受它,只发出警告)。
未转义 <
和 >
也允许在注释中使用,因此可以欺骗这种简单的正则表达式。
如果 BeautifulSoup 没有处理这个问题,它可能是一个错误,或者可能是一个有意识的设计决定,使其更能适应属性中丢失的右引号。
关于html - ">"(U+003E GREATER-THAN SIGN) 是否允许在 html 元素属性值内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/94528/