python - 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)
解决方案
检查请求的返回码:
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
在一段时间内保持不变(它可能是随机的)。
推荐阅读
- r - 如何在r中的列表上制作列联表
- postgresql - 使用 PostgreSQL 进行关键字搜索
- java - 从动态创建的 JTextField 中获取值
- wpf - 以编程方式设置时,讲述人不读取复选框状态
- json - Angular 5.2.10 - TypeScript 2.4.2 属性访问器 json 映射
- c# - C# EF6 映射未应用于选择
- python - 鲍鱼数据集准确率低
- c++ - 如何将单例类信号连接到主窗口类插槽或方法
- jenkins - Jenkins Build / Pipeline 作业 - 树中的作业列表 / 布局有序列表
- html - 将图像放在 HTML 中的文本上