首页 > 解决方案 > 使用 Scrapy 获取所有文章

问题描述

我将此脚本与 Scrapy 一起使用:

import scrapy


class PageSpider(scrapy.Spider):
    name = "page"
    start_urls = ['http://blog.theodo.com/']

    def parse(self, response):
        for article_url in response.css('.Link-sc-19p3alm-0 fnuPWK a ::attr("href")').extract():
            yield response.follow(article_url, callback=self.parse_article)

    def parse_article(self, response):
        content = response.xpath(".//div[@class='entry-content']/descendant::text()").extract()
        yield {'article': ''.join(content)}

我正在学习教程,但我猜有些部分需要更改。

我已经改变了:

response.css('.Link-sc-19p3alm-0 fnuPWK a ::attr("href")').extract():

我想这是我获取文章链接所需要的->

关联

但我坚持使用xpath。文章的所有内容都包含在一个 div 中,但不再有 entry-content :

路径

我想知道我是否在 response.css 中放入了正确的东西,以及我需要在 xpath 中编写的路径并理解其背后的逻辑。

谢谢你,我希望我的帖子很清楚:)

标签: python-3.xweb-scrapingscrapy

解决方案


打开你的终端,写下scrapy shell 'blog.theodo.com'

对于你必须做的 href 元素:

response.xpath('//a[@class="Link-sc-19p3alm-0 fnuPWK"]/@href').get()

我也不能给你一个“文本”的例子,因为你的图片没有为我显示足够的信息。

还要记住:如果你使用 ' 作为你的第一个引号,你必须在 class= 之后使用双引号,例如('//div[@class=""]')

对于https://www.formatic-centre.fr/formation/dynamiser-vos-equipes-special-post-confinement/上的整篇文章

response.xpath('//div[@class="course-des-content"]//text()').getall()

.get() 将为您提供第一场比赛,但在这种情况下,getall 更适合 imo


推荐阅读