当抓取完成时,我想从所有已爬网的数据创建一个数据框

时间:2018-11-29 15:19:44

标签: python pandas scrapy

我正在尝试抓取一些网站。我想将所有抓取的数据存储在名为Tabel_Final的最终数据框中。我将每个属性存储在不同的列表中,然后尝试将列表连接到最终数据框中,然后将其输出为csv以验证结果。我在代码中使用了另一种方法,在该方法中,我将直接在CSV中抓取的所有数据附加到csv中,但是我将需要该数据框很多:(有什么帮助吗?

这是我的代码:

import scrapy
import json
import csv
import re
import pandas as pd


name_list = []
category_list = []
type_list = []
model_list = []
model_name_list = []
model_code_list = []
Tabel_Final = pd.DataFrame(columns=['Country','Category', 'Type', 'Model', 'Name', 'SKU'])

class QuotesSpider(scrapy.Spider):
    name = "quotes1"

    def start_requests(self):
        with open('input.csv','r') as csvf:
            urlreader = csv.reader(csvf, delimiter=',',quotechar='"')
            for url in urlreader:
                if url[0]=="y":
                    yield scrapy.Request(url[1])

    def parse(self, response):

        regex = re.compile(r'"product"\s*:\s*(.+?\})', re.DOTALL)
        regex1 = re.compile(r'"pathIndicator"\s*:\s*(.+?\})', re.DOTALL)
        source_json1 = response.xpath("//script[contains(., 'var digitalData')]/text()").re_first(regex)
        source_json2 = response.xpath("//script[contains(., 'var digitalData')]/text()").re_first(regex1)
        model_code = response.xpath('//script').re_first('modelCode.*?"(.*)"')
        name = response.xpath("//meta[@property='og:country-name']/@content").extract_first()
        source_arr = response.xpath("//script[contains(., 'COUNTRY_SHOP_STATUS')]/text()").extract()
        color = response.xpath("//div[@class='product-details__toggler-info-title']//span[@class='product-details__toggler-selected']/@title").extract()

        if source_json1 and source_json2:
            source_json1 = re.sub(r'//[^\n]+', "", source_json1)
            source_json2 = re.sub(r'//[^\n]+', "", source_json2)
            product = json.loads(source_json1)
            path = json.loads(source_json2)
            product_category = product["pvi_type_name"]
            product_type = product["pvi_subtype_name"]
            product_model = path["depth_5"]
            product_name = product["model_name"]


        if source_json1 and source_json2:
            source1 = source_json1[0]
            source2 = source_json2[0]

            name_list.append(name)
            category_list.append(product_category)
            type_list.append(product_type)
            model_list.append(product_model)
            model_name_list.append(product_name)
            model_code_list.append(model_code)

            with open('output.csv','a',newline='') as csvfile:
                fieldnames = ['Country','Category','Type','Model','Name','SK','Color']
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                if product_category:
                    writer.writerow({'Country': name, 'Category': product_category, 'Type': product_type, 'Model': product_model, 'Name': product_name, 'SK': model_code, 'Color': color})

        if source_arr:
            categorie = re.findall('product.pvi_type_name.*"(.*)"', source_arr[0])
            tip = re.findall('product.pvi_subtype_name.*"(.*)"', source_arr[0])
            model = re.findall('product.displayName.*"(.*)"', source_arr[0])
            model_nume = re.findall('product.model_name.*"(.*)"', source_arr[0])

            name_list.append(name)
            category_list.append(categorie)
            type_list.append(tip)
            model_list.append(model)
            model_name_list.append(model_nume)
            model_code_list.append(model_code)

            with open('output.csv', 'a',newline='') as csvfile:
                fieldnames = ['Country','Category','Type','Model','Name','SK','Color']
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writerow({'Country': name, 'Category': categorie, 'Type': tip, 'Model': model, 'Name': model_nume, 'SK': model_code, 'Color': color})

        Tabel_Final.append(list(zip(name_list, category_list, type_list, model_list, model_name_list, model_code_list)))
        return Tabel_Final

1 个答案:

答案 0 :(得分:1)

我建议您拆分代码库:

  1. 用于抓取所需数据并将其导出为CSV或JSON Lines格式的抓人项目

  2. 一个单独的脚本,在该脚本中,将输出加载到Pandas DataFrame中,然后使用它进行任何操作

否则,您应该学习how to run Scrapy from a script并相应地重构代码。我有一个遵循这种方法的宠物项目:

  1. I defined a Scrapy pipeline,它将所有抓取的数据存储到模块变量中。

  2. 然后我从脚本as documented中执行蜘蛛程序,并且在抓取完成后在import and read the module variable中存储数据。