eLRuLL обеспечил еще более элегантный и лучший ответ на мой вопрос. Его решения следующие:
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()
Старый ответ:
Узел <script>
имеет только дочерние текстовые типы. Вот почему XPath не углубляется в тег <script>
. Но я нашел способ обойти это.
#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()