首页 > 解决方案 > Beutifulsoup 有时打印 None 有时

问题描述

我试图从 reddit 帖子中抓取图像。但是当我运行这个代码片段时,它有时会显示 html 片段,但有时它会打印 None(没有发生错误)。谁能告诉我为什么?这是代码。

from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.reddit.com/r/programmingmemes/').text
soup = BeautifulSoup(source, 'lxml')

img = soup.find('div', class_='_3Oa0THmZ3f5iZXAQ0hBJ0k')
print(img)

标签: pythonbeautifulsouppython-requests

解决方案


检查请求的返回码:

from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.reddit.com/r/programmingmemes/')

if source.status_code == 200:
    soup = BeautifulSoup(source.text, 'lxml')

    img = soup.find('div', class_='_3Oa0THmZ3f5iZXAQ0hBJ0k')
    print(img)
else:
    print(f"Error (code {source})")

还要检查是否class在一段时间内保持不变(它可能是随机的)。


推荐阅读