简体   繁体   English

Beutifulsoup 有时打印 None 有时

[英]Beutifulsoup sometimes print None sometimes

I tried to scrape a image from a reddit post.我试图从 reddit 帖子中抓取图像。 But when I run this code snippet It show me html snippet sometimes, but sometimes it prints None (NO Error occurred).但是当我运行这个代码片段时,它有时会显示 html 片段,但有时它会打印无(没有发生错误)。 Anybody can tell me why?谁能告诉我为什么? Here is the code.这是代码。

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)

Check the return code of the request:检查请求的返回码:

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})")

Also check if the class is constant during time (it may be randomized).还要检查class在一段时间内是否恒定(可能是随机的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM