换句话说,可以使用/<tag[^>]*>.*?<\/tag>/正则表达式来匹配tag不包含嵌套tag元素的html 元素吗?
例如(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>
Run Code Online (Sandbox Code Playgroud)
正则表达式:
$ perl -nE"say $1 if m~<div[^>]*>(.*?)</div>~" lt.html
Run Code Online (Sandbox Code Playgroud)
和屏幕刮刀:
#!/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
Run Code Online (Sandbox Code Playgroud)
两者都给出相同的输出:
1
">2
Run Code Online (Sandbox Code Playgroud)
预期产量:
1
2
Run Code Online (Sandbox Code Playgroud)
w3c说:
属性值是文本和字符引用的混合,除了文本不能包含模糊符号的附加限制.
是的,允许(W3C Validator接受它,只发出警告).
非转义<,>也允许内部评论,所以这样简单的正则表达式可以被愚弄.
如果BeautifulSoup没有处理这个问题,那么它可能是一个错误,或者可能是一个有意识的设计决定,使其更容易在属性中缺少关闭引号.