Skip to main content
 首页 » 编程设计

python之使用 Beautiful soup 的类属性

2025年01月19日9jillzhang

我在使用 Beautiful Soup 时遇到类属性问题。

我的代码是:

ls = ([x.get_text().strip('\n') for x in bs.find_all("div",{"class":"other-info","class":"description","class":"n-title search-detail"})]) 

但我只得到描述类而不是其他类信息。如何在同一代码中获取其他类信息。

请您参考如下方法:

首先,您可以将 strip=True 与 get_text() 一起使用函数去除文本中的所有空白。其次,字典不能有重复的键。 find_all() 函数接受一个 list 作为属性的值。此外,列表周围的括号 () 是多余的。删除它们。

使用这个:

ls = [x.get_text(strip=True) for x in bs.find_all("div", {"class": ["other-info", "description", "n-title search-detail"]})]