【问题标题】:How can I scrape multiple pages with scrapy in my python code?如何在我的 python 代码中使用 scrapy 抓取多个页面?
【发布时间】:2021-07-19 20:10:43
【问题描述】:

所以我目前正在为这个网站制作一个爬虫项目:https://www.datacenters.com/locations?page=1&per_page=40&query=&withProducts=false&showHidden=false&nearby=false&radius=0&bounds=&circleBounds=&polygonPath=。它遍历所有不同的数据中心位置并打印出 csv(通过 vs 代码完成并使用终端命令 scrapy crawl datacenters -o datacenters.csv 运行)。也许我应该改用 JSON 文件?也在考虑使用熊猫。出于某种原因,无论我改变什么,我的代码都不能超过第一页。我将不胜感激任何帮助,谢谢。我只需要知道要编辑/添加的其他内容,以便我可以抓取大部分(如果不是全部)页面,可能会创建一个循环?

import scrapy
import pandas as pd

class DatacentersSpider(scrapy.Spider):
  name = 'datacenters'
  allowed_domains = ['datacenters.com']
  start_urls = ['http://datacenters.com/locations']

def parse(self, response):
    for link in response.css('div.LocationsSearch__location__J7LUu a::attr(href)'):
        yield response.follow('https://www.datacenters.com'+link.get(), callback = self.get_info)

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()
        }

【问题讨论】:

    标签: python pandas web-scraping scrapy web-crawler


    【解决方案1】:

    如果您在浏览器中查看该页面,并在单击结果页面时记录您的网络流量,您会注意到向 REST API 端点发出 XHR HTTP GET 请求,其响应是 JSON 并包含给定页面的 40 个结果的所有仓库位置的大量信息。您可以模仿该请求,甚至可以定制查询字符串参数以一次获得 40 多个结果(注意 get_locationsparams 字典中的 per_page 键值对 - 默认为 "40" ,我已将其设置为 "3000" 以捕获所有 2591 个位置)。

    然而,API 的响应不包含电话号码或平方英尺 - 但它们包含每个位置的相对 slug URL。您可以导航到每个位置 URL,并从这些仓库特定页面中的每一个(方便地,将 JSON 放置在 <script> 标记中)中抓取缺失的信息:

    def get_locations():
        import requests
    
        url = "https://www.datacenters.com/api/v1/locations"
    
        params = {
            "page": "1",
            "per_page": "3000",
            "query": "",
            "withProducts": "false",
            "showHidden": "false",
            "nearby": "false",
            "radius": "0",
            "bounds": "",
            "circleBounds": "",
            "polygonPath": ""
        }
    
        headers = {
            "Accept": "application/json",
            "Accept-Encoding": "gzip, deflate",
            "User-Agent": "Mozilla/5.0"
        }
    
        response = requests.get(url, params=params, headers=headers)
        response.raise_for_status()
    
        yield from response.json()["locations"]
    
    
    def get_additional_info(location):
        import requests
        from bs4 import BeautifulSoup as Soup
        import json
    
        url = "https://www.datacenters.com" + location["url"]
    
        headers = {
            "Accept-Encoding": "gzip, deflate",
            "User-Agent": "Mozilla/5.0"
        }
    
        response = requests.get(url, headers=headers)
        response.raise_for_status()
    
        soup = Soup(response.content, "html.parser")
    
        script = soup.select_one("script[data-component-name=\"LocationProviderDetail\"]")
        content = json.loads(script.string)
    
        return content["location"]["phone"], content["location"]["grossBuildingSize"]
    
    
    def main():
    
        from itertools import islice
        
        for location in islice(get_locations(), 5):
            phone, sqft = get_additional_info(location)
            print("{}\n{}\n{}\n{}\n".format(
                location["name"],
                location["fullAddress"],
                sqft,
                phone
            ))
        return 0
    
    
    if __name__ == "__main__":
        import sys
        sys.exit(main())
    

    输出:

    IAD39 44274 Round Table Plaza Data Center
    Ashburn, VA, USA
    1057000 Sqft
    +1 877-882-7470
    
    IAD40 44372 Round Table Plaza Data Center
    Ashburn, VA, USA
    223200 Sqft
    +1 877-882-7470
    
    AWS IAD71 Data Center
    21263 Smith Switch Rd, Ashburn, VA, USA
    Not Available
    +1 844-902-4700
    
    AWS IAD60  Ashburn Data Center
    21267 Smith Switch Road, Ashburn, VA, USA
    Not Available
    +1 844-902-4700
    
    Ashburn Data Center
    21635 Red Rum Drive, Ashburn, VA, USA
    71000 Sqft
    +1 877-215-2422
    
    >>> 
    

    这里我使用itertools.islice 只获得前五个结果,但你明白了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多