刮擦简单网站的棘手问题

2024-09-28 23:45:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Scrapy来设置一个简单的spider来定期检查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

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

我觉得我一定是弄乱了xpath字符串(我是新来摆弄xpath的,如果是这样的话,我也不会感到惊讶!),或者当我通过Scrapy访问时,我可能得到了一个不同版本的站点?在

有什么想法吗?在


Tags: textdividurlresponse文章extractitem
1条回答
网友
1楼 · 发布于 2024-09-28 23:45:00

循环中的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()。在

相关问题 更多 >