2016-09-20 2 views
0

Also, ich bin neu in der Welt der Web-Crawler und ich habe ein wenig Schwierigkeiten beim Crawlen einer einfachen JSON-Datei und das Abrufen von Links von ihm. Ich benutze Scrapy Framework, um dies zu erreichen.Crawling Links aus JSON-Datei

Meine JSON Beispieldatei:

{ 

"pages": [ 

{ 

    "address":"http://foo.bar.com/p1", 

    "links": ["http://foo.bar.com/p2", 

    "http://foo.bar.com/p3", "http://foo.bar.com/p4"] 

}, 

{ 

    "address":"http://foo.bar.com/p2", 

    "links": ["http://foo.bar.com/p2", 

    "http://foo.bar.com/p4"] 

    }, 

{ 

    "address":"http://foo.bar.com/p4", 

    "links": ["http://foo.bar.com/p5", 

    "http://foo.bar.com/p1", "http://foo.bar.com/p6"] 

    }, 

    { 

     "address":"http://foo.bar.com/p5", 

     "links": [] 

    }, 

    { 

     "address":"http://foo.bar.com/p6", 

     "links": ["http://foo.bar.com/p7", 

     "http://foo.bar.com/p4", "http://foo.bar.com/p5"] 

     } 

    ] 

    } 

Meine items.py Datei

import scrapy 
from scrapy.item import Item, Field 


class FoobarItem(Item): 
    # define the fields for your item here like: 
    title = Field() 
    link = Field() 

Meine Spinne Datei

from scrapy.spider import Spider 
from scrapy.selector import Selector 
from foobar.items import FoobarItem 

class MySpider(Spider): 
    name = "foo" 
    allowed_domains = ["localhost"] 
    start_urls = ["http://localhost/testdata.json"] 


    def parse(self, response): 
     yield response.url 

Schließlich würde Ich mag die Datei und geben die Links kriechen in dem Objekt ohne Duplikate, aber gerade jetzt kämpfe ich sogar um den JSon zu kriechen. Ich dachte, der obige Code würde durch das Json-Objekt kriechen und die Links zurückgeben, aber meine Ausgabedatei ist leer. Nicht sicher, was ich falsch mache, aber jede Hilfe würde geschätzt werden

Antwort

-1

So zuerst müssen Sie eine Möglichkeit haben, die JSON-Datei zu analysieren, json lib sollte gut tun. Dann wäre das nächste Bit, um Ihren Crawler mit der URL zu starten.

import json 

with open("myExample.json", 'r') as infile: 
    contents = json.load(infile) 

#contents is now a dictionary of your json but it's a json array/list 
#continuing on you would then iterate through each dictionary 
#and fetch the pieces you need. 

    links_list = [] 
    for item in contents: 
     for key, val in item.items(): 
       if 'http' in key: 
        links_list.append(key) 
       if 'http' in value: 
        if isinstance(value, list): 
         for link in value: 
           links_list.append(link) 
        else: 
         links_list.append(value) 
    #get rid of dupes 
    links_list = list(set(links_list)) 
#do rest of your crawling with list of links