【问题标题】:Scrapy only returns first resultScrapy 只返回第一个结果
【发布时间】:2015-04-06 23:03:46
【问题描述】:

我正在尝试抓取 here 中看到的预格式化 html。 但我的代码只返回 1 个价格,而不是全部 10 个价格。

这里看到的代码:

class MySpider(BaseSpider):
    name = "working1"
    allowed_domains = ["steamcommunity.com"]
    start_urls = ["http://steamcommunity.com/market/search/render/?query=&appid=440"]

    def parse(self, response):
        sel = Selector(response)
        price = sel.xpath("//text()[contains(.,'$')]").extract()[0].replace('\\r\\n\\t\\t\\t\\r\\n\\t\\t\\t','')
        print price

我是scrapy/xpath 的超级新手,所以我不太确定为什么它不打印价格的每个实例。

有什么建议吗?谢谢!

【问题讨论】:

  • 如果你想要所有元素,为什么[0] 在那里?

标签: python xpath web-scraping scrapy


【解决方案1】:

您将获得 xpath 匹配的第一个结果。相反,遍历所有这些:

for price in sel.xpath("//text()[contains(., '$')]").extract():
    print price.strip(r"\r\n\t")

打印($0.03 多次出现):

$0.03
$0.03
$0.03
$0.03
$0.03
$0.03
$0.03
$0.03
$0.03
$0.03

【讨论】:

  • 太棒了!如果我想退货而不是打印怎么办?再次感谢!
  • @5Y3WS 这是您需要使用Field(s) 创建一个Item 类并从您的parse() 方法返回该Item 的实例的时候。
猜你喜欢
  • 1970-01-01
  • 2014-04-17
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多