【问题标题】:Scrapy - Problems scraping simple websiteScrapy - 抓取简单网站的问题
【发布时间】:2016-01-06 14:55:58
【问题描述】:

我正在尝试使用 Scrapy 设置一个简单的蜘蛛来定期检查 a webpage 以提取已发布文章的简单数据(标题和摘要 url)。

我已经按如下方式设置了蜘蛛:

class JournalSpider(Spider):
    name = "journal"
    allowed_domains = ["ametsoc.org"]
    start_urls = [
        "http://journals.ametsoc.org/toc/wefo/current/"
    ]

    def parse(self, response):

        journalTitle = Selector(response).xpath('//*[@id="journalBlurbPanel"]/div[2]/h3/text()').extract()[0]
        journalIssue = Selector(response).xpath('//*[@id="articleToolsHeading"]/text()').extract()[0].strip()  # remove whitespace at start and end

        # find all articles for the issue and parse each one individually
        articles = Selector(response).xpath('//div[@id="rightColumn"]//table[@class="articleEntry"]')

        for article in articles:
            item = ArticleItem()
            item['journalTitle'] = journalTitle
            item['journalIssue'] = journalIssue
            item['title'] = article.xpath('//div[@class="art_title"]/text()').extract()[0]
            item['url'] = article.xpath('//a/@href').extract()[0]
            yield item

这成功拉取了journalTitlejournalIssue,甚至迭代了25次,这是页面上的文章数,但是每篇文章都有相同的title(第一篇文章的标题)。此外,我不知道url 是从哪里提取的,因为它与我在页面上看到的任何内容都没有关联:/action/ssostart?idp=https%3A%2F%2Fshib.ametsoc.org%2Fshibboleth%2Fidp

我觉得我要么弄乱了我的 xpath 字符串(我是新来摆弄 xpath,所以如果是这种情况,我不会感到惊讶!),或者我得到了一个不同的版本通过 Scrapy 访问该网站时?

有什么想法吗?

【问题讨论】:

    标签: python xpath web-scraping scrapy


    【解决方案1】:

    循环中的 XPath 表达式必须特定于上下文并以点开头

    item['title'] = article.xpath('.//div[@class="art_title"]/text()').extract()[0]
    item['url'] = article.xpath('.//a/@href').extract()[0]
    

    您也可以使用extract_first() 方法代替extract()[0],并使用response.xpath() 快​​捷方式代替Selector(response).xpath()

    【讨论】:

    • 这样一个简单的解决方案,就像他们经常使用的那样。也感谢您提供额外的语法提示。
    • 嘿@alecxe . 在 xpath 中意味着什么?
    • @NikhilParmar 这基本上意味着 - 从当前节点开始遍历和搜索,而不是从文档根目录开始。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2013-05-09
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多