正如上面提到的标题,我正在做网页抓取,我不知道如何在main_paragraphs函数中排除另一个div中的div:

import requests
from bs4 import BeautifulSoup

def scrape_minimalism():
    base_url = "https://www.theminimalists.com/minimalism/"
    
    response = requests.get(base_url)
    
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        
        title = soup.find('h1', class_='entry-title').text.strip()
        print('\n', title)
        
        main_paragraphs = soup.find('div', class_='entry-content').find_all('p', class_=lambda x: x != 'ymae')

        main_pcontent = '\n'.join(paragraph.text.strip() for paragraph in main_paragraphs)
        print('\n', main_pcontent)
            
        
scrape_minimalism()

我的目标是排除另一个更大的div容器class = 'entry-content'下的class = 'ymae'

这里的问题是,class 'entry-content'以下的网页的段落是未排序的,并且由于它没有其他容器,因此难以从中提取数据.所以这就是为什么它还包括另一个子div 'ymae'

我试着做extract()x.getx.split

推荐答案

IIUC,您可以首先 Select 要删除的所有标记,然后 Select .extract()个标记,然后从剩下的<p>个标记中获取文本:

import requests
from bs4 import BeautifulSoup


def scrape_minimalism():
    base_url = "https://www.theminimalists.com/minimalism/"

    response = requests.get(base_url)

    if response.status_code == 200:
        soup = BeautifulSoup(response.text, "html.parser")

        title = soup.find("h1", class_="entry-title").get_text(strip=True)
        print("\n", title)

        # delete tags you don't want first:

        for to_delete in soup.select(".ymae, .subscribe-line"):
            to_delete.extract()

        main_paragraphs = soup.select(".entry-content p")

        main_pcontent = "\n".join(
            paragraph.get_text(strip=True) for paragraph in main_paragraphs
        )
        print("\n", main_pcontent)


scrape_minimalism()

打印:


 What Is Minimalism?

 So what is thisminimalismthing? It’s quite simple: to be a minimalist you must live with less than 100 things, you can’t own a car or a home or a television, you can’t have a career, you must live in exotic hard-to-pronounce places all over the world, you must start a blog, you can’t have children, and you must bea young white male from a privileged background.

...

Python相关问答推荐

使用新的类型语法正确注释ParamSecdecorator (3.12)

如何标记Spacy中不包含特定符号的单词?

运行总计基于多列pandas的分组和总和

海运图:调整行和列标签

图像 pyramid .难以创建所需的合成图像

Python解析整数格式说明符的规则?

我对我应该做什么以及我如何做感到困惑'

改进大型数据集的框架性能

从旋转的DF查询非NaN值

用SymPy在Python中求解指数函数

在二维NumPy数组中,如何 Select 内部数组的第一个和第二个元素?这可以通过索引来实现吗?

30个非DATETIME天内的累计金额

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

使用SeleniumBase保存和加载Cookie时出现问题

仅使用预先计算的排序获取排序元素

我可以不带视频系统的pygame,只用于游戏手柄输入吗?''

使用np.fft.fft2和cv2.dft重现相位谱.为什么结果并不相似呢?

在pandas中,如何在由两列加上一个值列组成的枢轴期间或之后可靠地设置多级列的索引顺序,

BeatuifulSoup从欧洲志愿者服务中获取数据和解析:一个从EU-Site收集机会的小铲子

在MongoDB文档中仅返回数组字段