【问题标题】:Using Xpath to take more element of the same type使用 Xpath 获取更多相同类型的元素
【发布时间】:2015-10-11 01:33:55
【问题描述】:

我需要获取此页面中的所有答案,例如带有作者姓名和答案文本的结构。

https://answers.yahoo.com/question/index?qid=20151007080620AAVNtY1

如果我使用此代码

 item = YahooItem()
 text_to_gain = hxs.xpath('//a[contains(@class,"uname Clr-    b")]/text()').extract()
    if text_to_gain:
        item['author']= str(text_to_gain[0]).strip()
    else:
        item['author']= "Anonymous"

    item['type']="Answer"

    text_to_gain = hxs.xpath('//span[contains(@class,"ya-q-full-text")][@itemprop="text"]/text()').extract()
    if text_to_gain:
        item['text']= str(text_to_gain[0]).strip()
    else:
        item['text']= "NULL"
  yield item

我只取一个元素。 我也尝试更改 hxs 或使用迭代器,例如:

all_answer = hxs.xpath('//li[contains(@class,"Cf Py-14 ya-other-answer Pend-14 ")]').extract()

但不起作用

【问题讨论】:

  • 您可以编辑您的帖子以添加特定问题吗?很难说出你在问什么。
  • 能否提供你的蜘蛛的完整代码?

标签: python xpath web-crawler scrapy scrapy-spider


【解决方案1】:

您可以通过以下表达式获得所有答案和相关作者。 此表达式选择页面上的所有答案,包括最佳答案

all_answers = hxs.xpath("descendant::*[@itemtype='https://schema.org/Answer']");

现在对每个答案 answ 进行迭代,以下 xpath 表达式(相对于每个 answ 节点执行)将分别选择文本和作者

text = hxs.xpath(answ,"descendant::*[@itemprop='text']");
author = hxs.xpath(answ,"//a[starts-with(@class,'uname')]"); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2016-02-04
    相关资源
    最近更新 更多