如果soup找不到类或id,如何处理错误

2024-04-23 18:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

这个网站有时我会找到tab1和tab2,有时我会找到一个

<div id="tab1" ><div class="movieplay"><iframe src="youtube.com" frameborder="0" allowfullscreen></iframe></div> </div>
<div id="tab2" ><div class="movieplay"><iframe src="youtube.com" frameborder="0" allowfullscreen></iframe>

如果soup找不到tab1或tab2,我将使用此代码来处理错误

result = soup.find(id="tab1")
result2 = soup.find(id="tab2")
if result.find(class_="movieplay") in result or result2.find(class_="movieplay") in result2:
    frame = result.find_all('iframe')[0]['src']
    print(frame)
    frame2 = result2.find_all('iframe')[0]['src']
    print(frame2)
else:
    print("link not find")

当soup找不到tab2时返回此错误

frame2 = result2.find_all('iframe')[0]['src']

AttributeError: ' nonetype" object has no attribute 'find_all'

有人能告诉我,如果tab2在代码“linknotfind”中找不到,我怎么打印?你知道吗


Tags: divsrcidresultallfindtab1class
1条回答
网友
1楼 · 发布于 2024-04-23 18:35:39

请尝试以下代码:

# result is node with id="tab1" if found, otherwise- node with id="tab2" 
result = soup.find(id="tab1") or soup.find(id="tab2") 

# If at least one found
if result:
    result.find(class_="movieplay")
    ...
else:
    print("No elements found")

相关问题 更多 >