XPath:获取带标签和不带标签的案例的基础文本

XPath: Get underlying text for cases with and without a tag

有没有办法将这两个 XPath 合二为一?

//li[@itemprop="worksFor"]/span/div/a/text()

//li[@itemprop="worksFor"]/span/div/text()

背景是我想在我的剪贴画中看到组织,但它的呈现方式各不相同: https://github.com/wencakisa(带有 a 标签)

Expected result: @HackSoftware

https://github.com/djangofan(没有 a 标签)

Expected result: The Standard Insurance

//li[@itemprop="worksFor"]/span/div//text()
from lxml.html import fromstring

temp = response.xpath('//li[@itemprop="worksFor"]/span/div').get()
fromstring(temp).text_content().strip()

scrapy 中的默认解析器是 parsel,它充当 API uppon lxml。没有额外的依赖。

fromstring() returns 一个 lxml.html.HtmlElementHtmlElement.text_content() 遍历当前节点内的所有 elements/nodes,并连接所有文本。

lxml.html.HtmlElement

  • .iter()
  • .iter_text()
  • .text_content()