【问题标题】:Beutifulsoup sometimes print None sometimesBeautifulsoup 有时打印 None 有时
【发布时间】:2021-04-24 17:58:00
【问题描述】:

我试图从 reddit 帖子中抓取图像。但是当我运行这段代码 sn-p 它有时会显示 html sn-p ,但有时它会打印 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)

【问题讨论】:

    标签: python beautifulsoup python-requests


    【解决方案1】:

    查看请求的返回码:

    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 在一段时间内是否保持不变(可能是随机的)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多