【问题标题】:XPath code to obtain class text within another class?XPath 代码在另一个类中获取类文本?
【发布时间】:2020-11-16 06:47:46
【问题描述】:

通过检查页面的 HTML 代码片段:

<div class="wBox"> 
  <ul class="detailListHorizontal" id="firstBoxHeight">
    <li class="">
       <label class="">Category</label>
       <a href="https://www.boat24.com/en/powerboats/" title="Power Boats" class="">Power Boats</a>
    <li class="">
    <li class="">
       <label class="">Boat Type</label>
       <a href="https://www.boat24.com/en/powerboats/center-console-boat/?typ=2119" title="Center console boat" class="">Center console boat</a>
    <li class="">

我需要抓取 Power BoatsCenter console boat 字符串。

这是我迄今为止尝试过的:

response.xpath("//label[contains(.,'Category')]/following-sibling::text()").extract() = empty list
response.xpath("//label[contains(.,'Category')]/a/text()").extract() = empty list
response.xpath("//label[contains(.,'Category')]/text()").extract() = returns 'Category'

有人有什么想法吗?

【问题讨论】:

  • 还有其他不想选择的兄弟&lt;li&gt;标签吗?还是只有那两个?
  • 是的,我不想选择许多其他兄弟&lt;li&gt; 类。

标签: html python-3.x dom xpath scrapy


【解决方案1】:

这个 XPath,

//label[. = 'Category' or . = 'Boat Type']/following-sibling::a/text()

将选择 labels 后面的那些 a 元素的文本,其字符串值为 'Category''Boat Type',

Power Boats
Center console boat

根据要求。

如果label 元素有空格变化,请将. = 替换为normalize-space() =

【讨论】:

  • 正是我想要的。谢谢。
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多