如何从Scrapy选择器中提取原始HTML?


问题内容

我正在使用response.xpath(’//
*’)re_first()提取js数据,然后将其转换为python本机数据。问题是提取/重新方法似乎没有提供不取消引用html的方法,即

原始HTML:

{my_fields:['O'Connor Park'], }

提取输出:

{my_fields:['O'Connor Park'], }

将此输出转换为json将不起作用。

最简单的方法是什么?


问题答案:

简短答案:

  • Scrapy / Parsel选择.re().re_first()方法取代HTML实体(除<&
  • 而是使用.extract().extract_first()获取原始HTML(或原始JavaScript指令),re并对提取的字符串使用Python的模块

长答案:

让我们看一下示例输入以及从HTML提取Javascript数据的各种方法。

HTML示例:

<html lang="en">
<body>
<div>
    <script type="text/javascript">
        var i = {a:['O&#39;Connor Park']}
    </script>
</div>
</body>
</html>

使用scrapy
Selector(使用下面的parsel库),您可以通过多种方式提取Javascript代码段:

>>> import scrapy
>>> t = """<html lang="en">
... <body>
... <div>
...     <script type="text/javascript">
...         var i = {a:['O&#39;Connor Park']}
...     </script>
...     
... </div>
... </body>
... </html>
... """
>>> selector = scrapy.Selector(text=t, type="html")
>>> 
>>> # extracting the <script> element as raw HTML
>>> selector.xpath('//div/script').extract_first()
u'<script type="text/javascript">\n        var i = {a:[\'O&#39;Connor Park\']}\n    </script>'
>>> 
>>> # only getting the text node inside the <script> element
>>> selector.xpath('//div/script/text()').extract_first()
u"\n        var i = {a:['O&#39;Connor Park']}\n    "
>>>

现在,使用.re(或.re_first)您将获得不同的结果:

>>> # I'm using a very simple "catch-all" regex
>>> # you are probably using a regex to extract
>>> # that specific "O'Connor Park" string
>>> selector.xpath('//div/script/text()').re_first('.+')
u"        var i = {a:['O'Connor Park']}"
>>> 
>>> # .re() on the element itself, one needs to handle newlines
>>> selector.xpath('//div/script').re_first('.+')
u'<script type="text/javascript">'    # only first line extracted
>>> import re
>>> selector.xpath('//div/script').re_first(re.compile('.+', re.DOTALL))
u'<script type="text/javascript">\n        var i = {a:[\'O\'Connor Park\']}\n    </script>'
>>>

HTML实体&#39;已被撇号代替。这是由于实现中的w3lib.html.replace_entities()调用.re/re_first(请参见函数中的parsel源代码extract_regex),仅在调用extract()extract_first()