首页 > 解决方案 > 如何从美丽的汤中排除特定的类(python)

问题描述

from bs4 import BeautifulSoup

import requests

source = requests.get('http://photographyblogger.net/26-beautiful-horse-pictures/').text
soup = BeautifulSoup(source, features="html.parser")


post = soup.find('article','full')
title = post.h2.text

for summery in post.find_all('p'):      
    rest = post.find("p", "wp-caption-text");
    rest.decompose()
    print(summery.text)

我想要实现的是打印标题,打印内容,然后打印标题,但目前没有使用休息,我将所有内容和标题放在一起。在此处输入图像描述,如您所见,如果我使用此代码,我得到了我想要的,但有一些错误

标签: pythonbeautifulsoup

解决方案


似乎您的循环post.find_all('p')列出了所有'p'元素,而在循环内您正在调用find()整个'post'元素,如果"p", "wp-caption-text"元素较少'summery',那么您的rest行将为空,这意味着调用.decompose()空字符串会产生错误'NoneType' object has no attribute 'decompose',而您仍然可以查看您期望的所有线路。


推荐阅读