如何用BeautifulSoup的find_all方法查找具有特定属性的XML标签?
- 内容介绍
- 文章标签
- 相关推荐
本文共计780个文字,预计阅读时间需要4分钟。
在XML中,常见的命名空间声明如下:
必须显式传入命名空间字典,且标签名要按实际前缀写(不能省略):
- 如果XML有
<rss xmlns="http://purl.org/rss/1.0/">,得用find_all("{http://purl.org/rss/1.0/}item") - 如果用前缀如
<feed xmlns:atom="http://www.w3.org/2005/Atom"><atom:link>,就得写find_all("atom:link", namespaces={"atom": "http://www.w3.org/2005/Atom"}) - 命名空间字典的key是前缀(如
"atom"),value是完整URI,大小写和斜杠必须完全一致
属性值含空格或特殊字符,用字典传参别用字符串
find_all("item", attrs={"pubDate": "Mon, 01 Jan 2024 00:00:00 GMT"})看着对,但实际可能匹配失败——XML属性值常有前后空格、换行或不可见字符。
本文共计780个文字,预计阅读时间需要4分钟。
在XML中,常见的命名空间声明如下:
必须显式传入命名空间字典,且标签名要按实际前缀写(不能省略):
- 如果XML有
<rss xmlns="http://purl.org/rss/1.0/">,得用find_all("{http://purl.org/rss/1.0/}item") - 如果用前缀如
<feed xmlns:atom="http://www.w3.org/2005/Atom"><atom:link>,就得写find_all("atom:link", namespaces={"atom": "http://www.w3.org/2005/Atom"}) - 命名空间字典的key是前缀(如
"atom"),value是完整URI,大小写和斜杠必须完全一致
属性值含空格或特殊字符,用字典传参别用字符串
find_all("item", attrs={"pubDate": "Mon, 01 Jan 2024 00:00:00 GMT"})看着对,但实际可能匹配失败——XML属性值常有前后空格、换行或不可见字符。

