>>> import scrapy
>>> t = """<html lang="en">
... <body>
... <div>
... <script type="text/javascript">
... var i = {a:['O'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'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'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>'
>>>
简短回答:
.re()
和.re_first()
方法替换HTML实体(除了<
,&
).extract()
或.extract_first()
获取原始HTML(或原始JavaScript指令),并对提取的字符串使用Python的re
模块长答案:
让我们看一个示例输入和从HTML中提取Javascript数据的各种方法。
HTML示例:
使用scrapy选择器(它使用下面的parsel库),您可以使用多种方法提取Javascript片段:
现在,使用
.re
(或.re_first
)可以得到不同的结果:HTML实体} 调用(请参阅} 函数中)导致的,在简单调用
'
已被apostrophe替换。这是由于.re/re_first
实现中的^{parsel
源代码,在^{extract()
或extract_first()
时不使用该调用您还可以使用
Selector
类extract
方法使用的相同函数,但参数不同:由于parsel 1.2.0(2017-05-17),您可以将
replace_entities=False
传递给re
和re_first
以避免默认行为。相关问题 更多 >
编程相关推荐