Beautifulsoup.find, attrs 多条件的问题

335 天前
 pppguest3962

hSection 是<class 'bs4.element.ResultSet'>
在使用 find 时:
hSection.find_all('div',attrs={'class':'bts'))
但结果还是很多不要的,实际上条件还要多一些,
如:
在以上条件前提下,还要属性'style'不能是'display:none;'

虽然紧接着多写几句 if ,for .children ,也能最终找到目标节点,
但想问,能否在 find() & find_all()方法里,一句就写完“是和非”的多条件完全匹配呢?

599 次点击
所在节点    Python
5 条回复
deplivesb
335 天前
results = soup.findAll(lambda tag: tag.attrs.get("class") == ["bts"] and tag.attrs.get("style") == "display:none")
deplivesb
335 天前
@deplivesb 忘了你要 div
soup.findAll(lambda tag: tag.name == "div" and tag.attrs.get("class") == ["bts"] and tag.attrs.get("style") == "display:none")
deplivesb
335 天前
@deplivesb #2

soup.findAll(lambda tag:
tag.name == "div" and
tag.attrs.get("class") == ["bts"] and
"display:none" not in tag.attrs.get("style", [])
)
pppguest3962
335 天前
@deplivesb

谢谢,有个情况是否能兼顾到而且避免?,
如:
tag.attrs.get("style", [])
或者
tag.attrs.get("class")
有些标签是没有 clss 或者 style 属性的,get 会有 None ,None 不能 iterable ,就异常了。。。
TypeError: argument of type 'NoneType' is not iterable
deplivesb
334 天前
@pppguest3962 get 的第二个参数不是默认值?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/946369

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX