我正在使用for循环在不同的html页面上进行web抓取,我需要为每个页面找到一个特定的标记(我使用的是BeautifulSoup和find_all方法)。但并不是在所有标签存在的页面中。所以我需要找到一种简单的方法来检查标签是否存在。为了检查标签是否不存在,我尝试编写了这段代码,但是它不工作。
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [92], in <cell line: 5>()
36 sal_play = salary.find_all('tr')[1:]
37 print(sal_play)
---> 38 if sal_play.find_all('tr', class_='thead') is None :
39 print('1')
40 else:
AttributeError: 'list' object has no attribute 'find'发布于 2022-10-29 19:50:07
正如错误消息所指出的,不能直接在列表上运行find --必须在每个项上运行它
如果您只想在没有标题行的情况下打印“1”,请使用:
if not [s for s in sal_play if s.find('tr', class_='thead')]:
print('1')或者,如果您想打印“1”,只要其中一些没有标题行,请使用:
if [s for s in sal_play if s.find('tr', class_='thead') is None]:
print('1')顺便说一句,如果标签不存在,find_all将返回一个空列表([]),find将返回None,因此if ...find_all(....) is None: do x将几乎确保x永远不会发生.
https://stackoverflow.com/questions/74147426
复制相似问题