re通常认为使用模块来解析xml或html是不好的做法。仅当 您
负责尝试解析的页面时才使用它。如果不是,则您的正则表达式非常复杂,或者如果有人替换
<input type="hidden"name=.../>为
<input name="..." type="hidden" .../>或几乎替换为其他任何内容,则脚本可能会中断。
BeautifulSoup是一个HTML解析器,它可以:
- 自动修复较小的错误(未关闭的标签…)
- 建立一个DOM树
- 允许您浏览树,搜索具有特定属性的特定标签
- 适用于Python 2和3
除非有充分的理由不这样做,否则应使用它而不是
reHTML解析。
例如,假设
txt包含整个页面,则查找所有隐藏字段将非常简单:
from bs4 import BeautifulSoupsoup = BeautifulSoup(txt)hidden_tags = soup.find_all("input", type="hidden")for tag in hidden_tags: # tag.name is the name and tag.value the value, simple isn't it ?


