【问题标题】:Set conditions on xpath statement在 xpath 语句上设置条件
【发布时间】:2019-06-02 15:51:42
【问题描述】:

我正在使用scrapy抓取一个网站,并且只想从灰色链接中获取数据,我通过将css类定位为灰色元素来完成。我面临的问题是第二个 xpath /div[1]/text() 正在从活动元素中选择元素,所以当我的列表返回时,我有列表中不活动的公司的地址。

我想知道是否有办法只从类 font_grey 中选择父 div。我确实尝试过使用parent::text(),但它返回了一个空值。

<div onclick="" class="col-md-5 border_right maxhelem ">
<h3 class="font_grey">Kost A/S</h3>
501&nbsp;Give St
</div>

response.xpath('//*[@id="main_wrapper"]/main/div/div/div/div[4]/div/div/div[2]/div[2]/div/div/div/div/div/div/h3[@class="font_grey"]/text() |  //*[@id="main_wrapper"]/main/div/div/div/div[4]/div/div/div[2]/div[2]/div/div/div/div/div/div[1]/text()').extract()

【问题讨论】:

    标签: python-3.x xpath scrapy css-selectors


    【解决方案1】:

    如果有办法只从类 font_grey 中选择父 div

    试试这个 xpath //*[@class='font_grey]/..

    解释:

    //* - 任何级别的任何元素
    [@class='font_grey'] - 类属性等于“font_grey”
    /.. - 选择父级

    【讨论】:

      【解决方案2】:

      这个 XPath,

      //div[h3/@class = "font_grey"]
      

      将选择所有div 元素以及h3 子元素的@class 属性值为"font_grey"

      【讨论】:

      • 有没有办法在其中添加 normalize-space() ?
      • 要达到什么目标?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 2018-12-15
      相关资源
      最近更新 更多