python - Scrapy:获取两个标识符之间的文本

标签 python xpath scrapy

我有以下使用 Scrapy 解析的 HTML:

<TD CLASS="dddefault">
    <SPAN class="fieldlabeltext">Associated Term: </SPAN>Fall 2015 - Qatar 
    <BR>
    <SPAN class="fieldlabeltext">Registration Dates: </SPAN>Apr 09, 2015 to Aug 27, 2015 
    <BR>
    <SPAN class="fieldlabeltext">Levels: </SPAN>Graduate, Undergraduate 
    <BR>
</TD>

我想获取第一个 SPAN 和 BR 之间的术语以及第二个 SPAN 和 BR 之间的日期之类的东西。

我试过这个:

term = response.xpath('//td[@class="dddefault"]/span[@class="fieldlabeltext"][1]/following-sibling::text()').extract()

date = response.xpath('//td[@class="dddefault"]/span[@class="fieldlabeltext"][2]/following-sibling::text()').extract()

但是这些也为我提供了其下方所有内容的文本。

有什么方法可以获取 SPAN 之后和 BR 之前的文本?

谢谢。

最佳答案

Is there any way I can get the text after the SPAN and before the BR?

“SPAN 之后” 部分标准很容易实现,因为 SPAN 是当前上下文节点,但是“BR 之前” 部分可能不像您那么容易认为是因为您的 HTML 示例中有多个 BR 元素(f.e Graduate, Undergraduate 也将在 BR 之前考虑,第 3 个 BR )。

因此,我建议采用一种不同的方法,即使用 XPath 位置索引 [1] 将结果限制为最近的后续同级文本节点,这将返回预期的文本节点,因为示例:

//td[@class="dddefault"]/span[@class="fieldlabeltext"][1]/following-sibling::text()[1]
//td[@class="dddefault"]/span[@class="fieldlabeltext"][2]/following-sibling::text()[1]

关于python - Scrapy:获取两个标识符之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517367/

相关文章:

java - 使用 Jython 调用 Java 子类的方法

python - 给定模块 m 和代码对象 c, "exec c in m.__dict__"做什么?

python - 类似 Xpath 的嵌套 python 字典查询

XPath 和 XML : Multiple namespaces

获取两个 i 标签之间信息的 CSS 选择器或 XPath?

python - Scrapy 处理 cookies/session/proxies

python - Pandas 在两个日期之间生成每周的第一个和最后一个工作日

python - Popen.communicate 被卡住,直到子进程产生的进程终止

python - 在 python 中使用 lxml 和 xpath 获取空列表

用于检查大 url 列表上断开链接的 Python 工具