Short answer:
- Scrapy/Parsel selectors'
.re()
and .re_first()
methods replace HTML entities (except <
, &
)
- instead, use
.extract()
or .extract_first()
to get raw HTML (or raw JavaScript instructions) and use Python's re
module on extracted string
Long answer:
Let's look at an example input and various ways of extracting Javascript data from HTML.
Sample HTML:
<html lang="en">
<body>
<div>
<script type="text/javascript">
var i = {a:['O'Connor Park']}
</script>
</div>
</body>
</html>
Using scrapy Selector, which is using the parsel library underneath, you have several ways of extracting the Javascript snippet:
>>> 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">
var i = {a:['O'Connor Park']}
</script>'
>>>
>>> # only getting the text node inside the <script> element
>>> selector.xpath('//div/script/text()').extract_first()
u"
var i = {a:['O'Connor Park']}
"
>>>
Now, Using .re
(or .re_first
) you get different result:
>>> # 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">
var i = {a:['O'Connor Park']}
</script>'
>>>
The HTML entity '
has been replaced by an apostrophe. This is due to a w3lib.html.replace_entities()
call in .re/re_first
implementation (see parsel
source code, in extract_regex
function), which is not used when simply calling extract()
or extract_first()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…