You need to enable JavaScript to run this app. 如何用Python+Scrapy实现datacenters.com多页数据爬取
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python+Scrapy实现datacenters.com多页数据爬取

问题解决说明

你的代码存在两个核心问题,导致只能抓取第一页数据:

  1. 代码缩进错误,parse和get_info方法没有放在DatacentersSpider类内部,属于基础语法问题
  2. 没有添加翻页逻辑,仅处理了初始的第一页请求

修复后的完整代码

import scrapy

class DatacentersSpider(scrapy.Spider):
    name = 'datacenters'
    allowed_domains = ['datacenters.com']
    # 直接从第一页的完整分页url发起请求,避免重定向问题
    start_urls = ['https://www.datacenters.com/locations?page=1&per_page=40&query=&withProducts=false&showHidden=false&nearby=false&radius=0&bounds=&circleBounds=&polygonPath=']

    def parse(self, response):
        # 处理当前页的所有数据中心详情链接
        for link in response.css('div.LocationsSearch__location__J7LUu a::attr(href)'):
            yield response.follow(f'https://www.datacenters.com{link.get()}', callback = self.get_info)
        
        # 新增翻页逻辑:提取下一页链接继续爬取
        # 方法1:通过页面下一页按钮提取链接,适配动态总页数
        next_page = response.css('li.Pagination__nextPage__3f6zq a::attr(href)').get()
        if next_page:
            yield response.follow(next_page, callback=self.parse)
        
        # 方法2:如果页面选择器失效,可手动构造分页url,提前确认总页数即可
        # current_page = int(response.url.split('page=')[1].split('&')[0])
        # next_page_num = current_page + 1
        # 例:总共有20页的情况,判断下一页页码不超过20
        # if next_page_num <= 20:
        #     next_page_url = f'https://www.datacenters.com/locations?page={next_page_num}&per_page=40&query=&withProducts=false&showHidden=false&nearby=false&radius=0&bounds=&circleBounds=&polygonPath='
        #     yield scrapy.Request(next_page_url, callback=self.parse)

    def get_info(self, response):
        yield {
            'Full Name': response.css('h1.LocationProviderDetail__locationNameXs__2UKtL::text').get(),
            'Number': response.xpath('//div[@class="LocationProviderDetail__phoneItemWrapper__3-SfO"]/div/span/text()').extract_first(),
            'SQFT': response.xpath('//div[@class="LocationProviderDetail__facilityDetails__M1ErX"]/div/span/text()').extract_first()
        }

补充说明

  • 运行命令依然可以使用你原来的scrapy crawl datacenters -o datacenters.csv直接导出CSV格式,需要导出JSON的话只需要把命令里的文件名后缀改为json即可
  • 后续数据处理不需要在爬虫代码里引入pandas,爬虫执行完成后直接读取导出的CSV/JSON文件再用pandas处理即可,逻辑更清晰
  • 如果遇到反爬限制,可以在项目settings.py中调整DOWNLOAD_DELAY参数,设置1-3秒的请求间隔,避免被站点封禁

内容的提问来源于stack exchange,提问作者Koder2000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 20:27:02