【问题标题】:Is there a scrapy following-sibling count?是否有一个scrapy的兄弟姐妹计数?
【发布时间】:2015-10-06 16:45:03
【问题描述】:

我正在尝试抓取以下 html 代码的标题:

<FONT COLOR=#5FA505><B>Claim:</B></FONT> &nbsp; Coed makes unintentionally risqu&eacute; remark about professor's "little quizzies."
<BR><BR>
<CENTER><IMG SRC="/images/content-divider.gif"></CENTER>

我正在使用此代码:

def parse_article(self, response):
             for href in response.xpath('//font[b = "Claim:"]/following-sibling::text()'):
                        print href.extract()

并且我成功地从上述 html 代码中提取了我想要的正确 Claim: 值,但它(以及同一页面中具有类似结构的其他内容)也提取了以下 html。我将我的xpath() 定义为只拉入名为Claim:font 标签,那么为什么它还要拉入下面的Origins?我该如何解决?我试着看看我是否只能得到下一个 following-sibling 而不是全部,但这没有用

<FONT COLOR=#5FA505 FACE=""><B>Origins:</B></FONT> &nbsp; Print references to the "little quizzies" tale date to 1962, but the tale itself has been around since the early 1950s. It continues to surface among college students to this day. Similar to a number of other college legends

【问题讨论】:

  • @JohnDene 我的输出发生了变化,但这只是一堆空白空间,每隔一段时间就会出现一个不常见的,
  • 我认为这是因为您正在使用 for 循环。如果我猜对了,您只想提取一个值吗?
  • 这更正确。现在可以使用了
  • 我不能要求你接受我的回答作为评论:p

标签: python xpath web-crawler scrapy


【解决方案1】:

我认为您的 xpath 缺少 text() 限定符(解释为 here)。应该是:

'//font/[b/text()="Claim:"]/following-sibling::text()'

【讨论】:

  • 仍然给我相同的输出。也拉入Origins
【解决方案2】:

following-sibling 轴返回元素后面的所有兄弟。如果您只想要第一个兄弟,请尝试 XPath 表达式:

//font[b = "Claim:"]/following-sibling::text()[1]

或者,取决于您的具体用例:

(//font[b = "Claim:"]/following-sibling::text())[1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-05-30
    • 2022-05-30
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2012-07-23
    • 1970-01-01
    相关资源
    最近更新 更多