如何用Python+Scrapy实现datacenters.com多页数据爬取
问题解决说明
你的代码存在两个核心问题,导致只能抓取第一页数据:
- 代码缩进错误,
parse和get_info方法没有放在DatacentersSpider类内部,属于基础语法问题 - 没有添加翻页逻辑,仅处理了初始的第一页请求
修复后的完整代码
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
相关产品推荐
相关产品推荐

