使用Scrapy中具有特定关键字的所有页面的URL创建JSON文件

时间:2014-07-24 09:52:26

标签: python json file scrapy

我在scrapy中解析多个URL /页面。在每个页面上,它搜索特定的关键字,如果找到,请在Attribute_Dictionary中附加URL。

因为,每个正在解析的URL,Attribute_Dictionary每次都会更新。现在我想在完成所有URL的解析时,只编写一个关于Attribute_Dictionary的json文件。

目前我编写了将内容转储到JSON的代码,但它一次又一次地创建JSON文件(在一次运行中)并覆盖最后创建的json文件。
所需的输出是一个json文件,其中包含Attribure_Dictionary中的所有URL。

请帮忙。我应该创建一个全局变量来处理所有被解析的页面吗?如果是,那该怎么办?

def parse(self, response):
    global parsed_urls
    global domain_urls
    global tld
    global sliced_url
    items = []
    global item



    if ('html' not in response.headers['Content-Type']):
        return

    sel = Selector(response)


    for h3 in sel.xpath('//title/text()').extract():
         #print h3 + "***********" + ' <' + response.url + '>'
         sliced_url = response.url.split('/')[2]


    for url in sel.xpath('//a/@href').extract():

        if (url.startswith('/')):

            url = 'http://' + sliced_url + url



        if (url in parsed_urls or len(url) > 250):
            continue

        parsed_urls.append(url)

        if tld in url:
            domain_urls.append(url)
            yield Request(url, callback=self.parse)

        #print parsed_urls
        for keyword in Keyword_Dictionary:

            if (url.startswith('http') and (tld in url)):
                if (self.Search_keyword_in_url(keyword, response)):
                    if keyword not in Url_Dictionary:
                        Url_Dictionary[keyword] = []
                    Url_Dictionary[keyword].append(url)
                    #print keyword + " " + "Detected"



        for keyword in Url_Dictionary:

            Attribute_Key = []
            Attribute_Key = Keyword_Dictionary.get(keyword)
            Attribute_Key_Value = Url_Dictionary.get(keyword)
            for key in Attribute_Key:
                if key not in Attribute_Dictionary:
                    Attribute_Dictionary[key] = []
                    print key
                    print "\n"
                    for value in Attribute_Key_Value:
                        if value not in Attribute_Dictionary.get(key):
                            Attribute_Dictionary[key].append(value)
                            print key + " " + "Just Appended"
                            item = Website()
                            Modified_Key = key.replace(" ","_")
                            item[Modified_Key] = response.url
                            print item[Modified_Key]

        print Attribute_Dictionary
        # Json Code
        fileptr = open('keywords_spider.json','a')
        json.dump(Attribute_Dictionary, fileptr, indent=4)
        print "Created keywords_spiders.json.."
        fileptr.close()




def Search_keyword_in_url(self, keyword, response):

    sel = Selector(response)

    text_list = sel.xpath('//div/p/text()').extract()
    for text in text_list:
        if text.find(keyword) > -1:
            return True
    return False

1 个答案:

答案 0 :(得分:2)

我认为这对于你想要完成的事情来说太复杂了。我会使用Item来帮助简化事情。阅读文档here。此外,尝试自己编写文件并不是最好的方法。使用Items让Scrapy为您处理输出。您可以使用Item Pipeline

轻松更改输出格式或扩展功能

如果您决定使用它们,我会留下一个解决方案。在项目中,创建与 spiders 目录处于同一级别的文件 items.py

#items.py

from scrapy.item import Item, Field

class myFunkyUrlItem(Item):
    url = Field()
    keyword = Field()

现在在你的刮刀中,使用现有的逻辑来查找元素。当您找到它们时,请创建myFunkyUrlItem

**#The Crawler!**
#import our custom item
from myProjectName.items import myFunkyUrlItem

def parse(self,response):
######Your existing scraper####
...
...
...

#When found
url_item = myFunkyUrlItem()    
url_item['url'] = response.url
url_item['keyword'] = the_keyword_found #Change this

#Give item to scrapy to process 
return url_item

现在,最后在运行爬虫时,告诉Scrapy转储所有找到的项目为json。

scrapy crawl myFunkySpider -o items.json

现在,

import json

my_items = json.load(open('items.json'))

print my_items[0]['url']
print my_items[0]['keyword']

我希望这会有所帮助。我仍然不太确定我理解你的问题。如果这不是你想要的,请评论!