使用XPath检索a<;脚本>;标签

使用XPath检索a<;脚本>;标签,xpath,scrapy,Xpath,Scrapy,我试图使用XPath获取页面上驻留在标记中的元素。例如: <div id="foo"> <script> <p>You can't get me.</p> </script> </div> 你抓不到我 如果我尝试response.xpath('//div[@id=“foo”]//p')或response.xpath('//div[@id=“foo”]/script/p'),两者都返回空数

我试图使用XPath获取页面上驻留在
标记中的元素。例如:

<div id="foo">
    <script>
        <p>You can't get me.</p>
    </script>
</div>

你抓不到我

如果我尝试
response.xpath('//div[@id=“foo”]//p')
response.xpath('//div[@id=“foo”]/script/p')
,两者都返回空数组

如何使用XPath获取
标记中的元素?

为我的问题提供了一个更加优雅和更好的答案。他的解决办法如下:

from scrapy import Selector

#First, retrieve the content within the <script> tag:
text = response.xpath('//script/text()').extract_first()
#Then, create a Selector
sel = Selector(text=text)
#Now we can use XPath normally as if the text was a common HTML response
sel.xpath(//p/text()).extract_first()
从刮片导入选择器
#首先,检索标记中的内容:
text=response.xpath('//script/text()')。首先提取
#然后,创建一个选择器
sel=选择器(文本=文本)
#现在我们可以正常使用XPath,就好像文本是一个常见的HTML响应一样
sel.xpath(//p/text()).extract_first()

旧答案:
节点只有文本类型的子节点。这就是为什么XPath不能深入
标记的原因。但是,我找到了解决办法

#First, retrieve the content within the <script> tag:
text = response.xpath('//script/text()').extract_first()
#Then, encode it
text_encoded = text.encode('utf-8')
#Now, convert it to a HtmlResponse object
text_in_html = HtmlResponse(url='some url', body=text_encoded, encoding='utf-8')
#Now we can use XPath normally as if the text was a common HTML response
text_in_html.xpath(//p/text()).extract_first()
#首先,检索标记中的内容:
text=response.xpath('//script/text()')。首先提取
#然后,对其进行编码
text_encoded=text.encode('utf-8')
#现在,将其转换为HtmlResponse对象
text_in_html=HtmlResponse(url='some url',body=text_encoded,encoding='utf-8')
#现在我们可以正常使用XPath,就好像文本是一个常见的HTML响应一样
xml.xpath(//p/text())中的text\u。首先提取

您的XPath表达式都正常。所以肯定还有一个错误,真的吗?我想应该怪
标签。。。也许我需要做一些进一步的调试。我真的不知道
标记是否是某种例外。如果是这样的话,我的评论应该被忽略。我认为是这样的。我刚刚使用控制台打开了元素,脚本节点不包含任何子节点。它只包含文本对象。不像人们通常期望的那样将HTML标记作为节点