Scrapy:从HTML脚本

时间:2016-07-19 23:47:19

标签: python html json xpath scrapy

我正在尝试从HTML脚本中提取(似乎是)JSON数据。 HTML脚本在网站上如下所示:

<script>
  $(document).ready(function(){
    var terms    = new Verba.Compare.Collections.Terms([{"id":"6436","name":"SUMMER 16","inquiry":true,"ordering":true},{"id":"6517","name":"FALL 16","inquiry":true,"ordering":true}]);
    var view     = new Verba.Compare.Views.CourseSelector({el: "body", terms: terms});
  });
</script>

我想提出以下内容:

[{"id":"6436","name":"SUMMER 16","inquiry":true,"ordering":true},{"id":"6517","name":"FALL 16","inquiry":true,"ordering":true}]

使用以下代码,我可以获得完整的脚本。

    def parse(self, response):
        print response.xpath('/html/body/script[2]').extract()

是否有一种简单的方法可以从该脚本中提取“id”,“name”等的值。或者,通过修改xpath有更直接的方法吗?我似乎无法使用firebug在xpath上更深入。

4 个答案:

答案 0 :(得分:3)

您可以使用js2xml

为了说明,首先,让我们用您的示例HTML创建一个Scrapy选择器,并获取JavaScript语句:

>>> import scrapy
>>> sample = '''<script>
...   $(document).ready(function(){
...     var terms    = new Verba.Compare.Collections.Terms([{"id":"6436","name":"SUMMER 16","inquiry":true,"ordering":true},{"id":"6517","name":"FALL 16","inquiry":true,"ordering":true}]);
...     var view     = new Verba.Compare.Views.CourseSelector({el: "body", terms: terms});
...   });
... </script>'''
>>> selector = scrapy.Selector(text=sample, type='html')
>>> selector.xpath('//script//text()').extract_first()
u'\n  $(document).ready(function(){\n    var terms    = new Verba.Compare.Collections.Terms([{"id":"6436","name":"SUMMER 16","inquiry":true,"ordering":true},{"id":"6517","name":"FALL 16","inquiry":true,"ordering":true}]);\n    var view     = new Verba.Compare.Views.CourseSelector({el: "body", terms: terms});\n  });\n'

然后我们可以用js2xml解析JavaScript代码。你得到一个lxml树:

>>> import js2xml
>>> jssnippet = selector.xpath('//script//text()').extract_first()
>>> jstree = js2xml.parse(jssnippet)
>>> jstree
<Element program at 0x7fc7c6bae1b8>

树是什么样的?它非常冗长:

>>> print(js2xml.pretty_print(jstree))
<program>
  <functioncall>
    <function>
      <dotaccessor>
        <object>
          <functioncall>
            <function>
              <identifier name="$"/>
            </function>
            <arguments>
              <identifier name="document"/>
            </arguments>
          </functioncall>
        </object>
        <property>
          <identifier name="ready"/>
        </property>
      </dotaccessor>
    </function>
    <arguments>
      <funcexpr>
        <identifier/>
        <parameters/>
        <body>
          <var name="terms">
            <new>
              <dotaccessor>
                <object>
                  <dotaccessor>
                    <object>
                      <dotaccessor>
                        <object>
                          <identifier name="Verba"/>
                        </object>
                        <property>
                          <identifier name="Compare"/>
                        </property>
                      </dotaccessor>
                    </object>
                    <property>
                      <identifier name="Collections"/>
                    </property>
                  </dotaccessor>
                </object>
                <property>
                  <identifier name="Terms"/>
                </property>
              </dotaccessor>
              <arguments>
                <array>
                  <object>
                    <property name="id">
                      <string>6436</string>
                    </property>
                    <property name="name">
                      <string>SUMMER 16</string>
                    </property>
                    <property name="inquiry">
                      <boolean>true</boolean>
                    </property>
                    <property name="ordering">
                      <boolean>true</boolean>
                    </property>
                  </object>
                  <object>
                    <property name="id">
                      <string>6517</string>
                    </property>
                    <property name="name">
                      <string>FALL 16</string>
                    </property>
                    <property name="inquiry">
                      <boolean>true</boolean>
                    </property>
                    <property name="ordering">
                      <boolean>true</boolean>
                    </property>
                  </object>
                </array>
              </arguments>
            </new>
          </var>
          <var name="view">
            <new>
              <dotaccessor>
                <object>
                  <dotaccessor>
                    <object>
                      <dotaccessor>
                        <object>
                          <identifier name="Verba"/>
                        </object>
                        <property>
                          <identifier name="Compare"/>
                        </property>
                      </dotaccessor>
                    </object>
                    <property>
                      <identifier name="Views"/>
                    </property>
                  </dotaccessor>
                </object>
                <property>
                  <identifier name="CourseSelector"/>
                </property>
              </dotaccessor>
              <arguments>
                <object>
                  <property name="el">
                    <string>body</string>
                  </property>
                  <property name="terms">
                    <identifier name="terms"/>
                  </property>
                </object>
              </arguments>
            </new>
          </var>
        </body>
      </funcexpr>
    </arguments>
  </functioncall>
</program>

您可以使用XPath技能指向JavaScript数组(您希望分配给new的{​​{1}}构造的“点”访问器的第一个参数:

var terms

最后,既然您拥有>>> jstree.xpath('//var[@name="terms"]') [<Element var at 0x7fc7c565e638>] >>> jstree.xpath('//var[@name="terms"]/new/arguments/*') [<Element array at 0x7fc7c565e5a8>] >>> jstree.xpath('//var[@name="terms"]/new/arguments/*')[0] <Element array at 0x7fc7c565e5a8> 元素,就可以将其传递给<array>以获得一个可以使用的好的Python对象(js2xml.jsonlike.make_dict()有点名字错误):

make_dict

注意:你也可以使用快捷方式>>> js2xml.jsonlike.make_dict(jstree.xpath('//var[@name="terms"]/new/arguments/*')[0]) [{'ordering': True, 'inquiry': True, 'id': '6436', 'name': 'SUMMER 16'}, {'ordering': True, 'inquiry': True, 'id': '6517', 'name': 'FALL 16'}] >>> 来获取看起来像Python字典或列表的所有内容(你得到2个列表,你对第一个列表感兴趣):

js2xml.jsonlike.getall()

答案 1 :(得分:0)

我会使用正则表达式提取它,例如:

response.xpath('/html/body/script[2]').re_first('\((\[.*\])\)')

答案 2 :(得分:0)

chompjs提供了将JavaScript对象解析为字典的API。

例如,如果JavaScript代码包含var data = {field: "value", secondField: "second value"};您可以按以下方式提取该数据:

import chompjs
javascript = response.css('script::text').get()
data = chompjs.parse_js_object(javascript)

最终结果是 {'field': 'value', 'secondField': 'second value'} 一个

答案 3 :(得分:-1)

你不能“更深入”,因为该元素的内容只是文本。从JavaScript中读出JSON并不难:

line = javascript.strip().splitlines()[1]
the_json = line.split('(', 1)[1].split(')', 1)[0]