使用Scrapy,我如何获得Javascript变量的值....
这是我的代码......
<script rel="bmc-data">
var match = 'yes';
var country = 'uk';
var tmData = {
"googleExperimentVariation": "1",
"pageTitle": "Child Care",
"page_type": "claimed",
"company_state": "wyostate",
"company_city": "mycity"
};
</script>
我想检查 page_type 变量的值。如果其“声明”处理该页面,或者继续前进....
我试过这个......
pattern = r'page_type = "(\w+)",'
response.xpath('//script[@rel="bmc-data"]').re(pattern)
但是当然这不起作用,因为我认为我的正则表达式是错误的。
答案 0 :(得分:2)
我可以建议使用js2xml
(免责声明:我写了js2xml)
>>> import scrapy
>>> import js2xml
>>> html = '''<script rel="bmc-data">
... var match = 'yes';
... var country = 'uk';
... var tmData = {
... "googleExperimentVariation": "1",
... "pageTitle": "Child Care",
... "page_type": "claimed",
... "company_state": "wyostate",
... "company_city": "mycity"
... };
... </script>'''
>>> selector = scrapy.Selector(text=html)
>>> selector.xpath('//script/text()').extract_first()
u'\n var match = \'yes\';\n var country = \'uk\';\n var tmData = {\n "googleExperimentVariation": "1",\n "pageTitle": "Child Care",\n "page_type": "claimed",\n "company_state": "wyostate",\n "company_city": "mycity"\n };\n'
>>> jscode = selector.xpath('//script/text()').extract_first()
>>> print(js2xml.pretty_print(jstree))
<program>
<var name="match">
<string>yes</string>
</var>
<var name="country">
<string>uk</string>
</var>
<var name="tmData">
<object>
<property name="googleExperimentVariation">
<string>1</string>
</property>
<property name="pageTitle">
<string>Child Care</string>
</property>
<property name="page_type">
<string>claimed</string>
</property>
<property name="company_state">
<string>wyostate</string>
</property>
<property name="company_city">
<string>mycity</string>
</property>
</object>
</var>
</program>
>>> jstree.xpath('//var[@name="tmData"]/object')[0]
<Element object at 0x7f0b0018f050>
>>> from pprint import pprint
>>> data = js2xml.jsonlike.make_dict(jstree.xpath('//var[@name="tmData"]/object')[0])
>>> pprint(data)
{'company_city': 'mycity',
'company_state': 'wyostate',
'googleExperimentVariation': '1',
'pageTitle': 'Child Care',
'page_type': 'claimed'}
>>> data['page_type']
'claimed'
>>>
答案 1 :(得分:2)
你的正则表达式模式有问题:
# you are looking for this bit: "page_type": "claimed",
re.findall('page_type": "(.+)"', html_body)
# ["claimed"]
或者在您的情况下scrapy选择器的上下文中:
response.xpath('//script[@rel="bmc-data"]').re('page_type": "(.+)"')
如果您需要解析多个这样的变量,我建议保罗提到的答案,因为正则表达式并不总是像xml解析一样可靠。