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

时间:2016-01-19 21:57:41

标签: python scrapy parsel

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

原始html:

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

提取输出:

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

将此输出转换为json将无效。

最简单的方法是什么?

3 个答案:

答案 0 :(得分:8)

简答:

  • Scrapy / Parsel选择器的.re().re_first()方法替换HTML实体(<&除外)
  • 相反,使用.extract().extract_first()获取原始HTML(或原始JavaScript指令)并在提取的字符串上使用Python的re模块

答案很长:

让我们看一下从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;已被apostrophe取代。这是由于.re/re_first实施中的w3lib.html.replace_entities()调用(请参阅extract_regex函数中的parsel源代码),仅在调用extract()extract_first()

答案 1 :(得分:1)

您还可以使用Selector类&#39;使用的相同功能。 extract方法,但有不同的参数:

from lxml import etree
etree.tostring(selector._root)

答案 2 :(得分:0)

自Parsel 1.2.0(2017-05-17)起,您可以将replace_entities=False传递给rere_first以避免默认行为。

相关问题