使用Scrapy,如何将Ajax背后的响应体作为JSON字符串?

时间:2013-12-23 13:51:07

标签: python json soap response scrapy

我在这里发布我的代码以寻求帮助,我只想将响应正文数据作为JSON字符串格式,但经过多次尝试后没有运气。

此数据位于SOAP Web服务之后,因为它在Ajax中加载数据,所以它不像XML或HTML格式那样正常。

# coding: utf8 

import json
from scrapy.spider import BaseSpider

# C. Crawl Stock Data
class StockSpider(BaseSpider):
    name = "stock"

# C1. SSI HOSE
allowed_domains = ["banggia2.ssi.com.vn"]
start_urls = ["http://banggia2.ssi.com.vn/AjaxWebService.asmx/GetHoseIndex"]

def parse(self, response):        
    datas = json.loads(response.body)
    # In Firebug -> Net -> XHR, Response Body is below
    # {"d":"64136@508.68|4.23 (0.84 %)|108210317|1470328|1|136|66|78|K|15:01:17|23/12/2013|1387785677000|0|18:09:17"}

    # Write json data, hope to get the same string like above
    f = open("stock_json_data.txt", "w")
    f.write( str(datas) )
    f.close()              

    # Result:  
    # 2013-12-23 20:40:58+0700 [stock] DEBUG: Gave up retrying <GET http://banggia2.ss
    # i.com.vn/AjaxWebService.asmx/GetHoseIndex> (failed 3 times): 500 Internal Server
    # Error

提前致谢!我会为你投票给你最好的答案!

[编辑]更多信息:在.NET中,我可以很容易地得到这些响应:

   WSTester.AjaxWebService service = new WSTester.AjaxWebService();
   string result = service.GetHoseIndex();

2 个答案:

答案 0 :(得分:1)

您可以通过这个小命令将输出呈现给JSON文件。

scrapy crawl <spider_name> -o items.json -t json

有关详细说明,请参阅本指南。 http://pypix.com/python/build-website-crawler-based-upon-scrapy/

答案 1 :(得分:0)

最后,我找到了一个解决方案,用户Scrapy + Selenium进行处理。这意味着我必须在弹出窗口中提交并捕获数据。

也许Scrapy的人应该支持Ajax Scraping来简化实现,与.NET相比。