使用scrapy抓取文本段落

0 投票
1 回答
57 浏览
提问于 2025-04-12 06:58

我现在正在用 scrapy 这个工具来抓取一个网站的数据。这个网站有很多子链接,我都能进入。每个子链接里有三样东西我需要:标题、描述和内容。我可以获取到标题和描述,但内容被分散在多个部分中,每个子链接的部分数量都不一样,就像这个例子所示:

enter image description here

我尝试用循环来遍历每个部分并存储它们,但使用 yield 函数时,只能得到标题、描述和最后一个部分的内容。

下面是代码:

def parse_instructions(self, response):
    title = response.xpath('//\*\[@id="d-article"\]/div\[1\]/div\[1\]/h1/text()').get()
    description = response.xpath('//\*\[@id="ency\_summary"\]/p/text()').getall()
    joined_description = ' '.join(description)
    sections = response.css('section div.section:not([class*=" "])')

    for section in sections:
        section_text = ' '.join(section.css('p::text').getall())
        section_text = ' '.join('a::text').getall()
        section_text = ' '.join('ul::text').getall()

    yield {
        "title": title,
        "description": joined_description,
        "section_text": section_text,
    }

相关问题:

1 个回答

暂无回答

撰写回答