[英]xpath: how to extract text before, AND within, AND after the <strong> element
[英]How to extract text which lies after <strong> tag in element
嘗試從元素中提取文本,如下所示:
<div><strong>"Beginning_of_text"</strong>"Rest_of_text"</div>
當我嘗試使用Scrapy shell提取"Rest_of_text"
,
response.css("div::text").extraxt()
它什么也沒給我。 我是否必須使用一些特殊命令來獲取位於元素內<strong>
標記之后的文本?
僅對於“ Rest_of_text”,可以使用response.xpath('//div/strong/following-sibling::text()').get()
給定您提供的文本,您提到的命令應該返回以下內容:
['"Rest_of_text"']
如果在strong
標簽之前有空格,則可能會出現此問題,例如:
<div> <strong>"Beginning_of_text"</strong>"Rest_of_text"</div>
在這種情況下,如果執行相同的命令,則會得到以下信息:
[' ', '"Rest_of_text"']
但是,如果在strong
標簽之后沒有任何內容,您將得到以下信息:
[' ']
處理我所知道的所有這些情況的最佳方法是執行以下操作:
>>> full_text = ''.join(response.xpath('//div//text()').extract())
>>> before_strong, after_strong = full_text.split(response.css('strong::text').extract_first())
因此,在您提供的文本中, before_strong
將等於''
, after_strong
將等於'"Rest_of_text"'
,這似乎就是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.