[英]How to extract the text of a text node within an html dom through xpath?
[英]How to find a particular string within a Source code(Xpath) and extract the proceeding text?
从以下源代码中:
<html>
...
<div>.......</div>
<script bounce ="bla">....</script>
<div>.......</div>
.
.
n
.
<script bounce="foo">....],[null,"bla bla"]........</script>
.
.
.
</html>
我想提取(bla bla),它明确地位于(,[null,“)之后直到点(”])之后,我之所以无法通过脚本名称id和div进行访问,是因为它们在我的每个页面中都是动态的米刮scrap。 因此,代码必须寻找(,[null,“)并提取后续文本。
您可以尝试查找脚本节点并使用XPath获取其文本:
node = html.select('//script[contains(., "[null,")]/text()').extract()
然后提取所需的子字符串:
node.split("[null,")[-1].split("]")[0]
value = response.xpath('//script[@bounce="foo"]/text()').re_first( r',\s*\[\s*null,\s*"([^"]+)' )
但是看起来您正在尝试在Javascript中解析某种JSON字符串,因此最好解析整个JSON,然后导航到您的字符串:
json_string = response.xpath('//script[@bounce="foo"]/text()').extract_first()
data = json.loads(json_string)
value = data[someindex][anotherindex][etc]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.