如何在 Scrapy 中使用 Xpath 提取文本?

How do I extract text with the Xpath in Scrapy?

好吧,我似乎已经尝试了一切,只是无法弄清楚这里发生了什么。我要抓取的网站的直接 link 是 http://www.ammofast.com/collections/pistol/products/aguila-25-auto-acp-full-metal-jacket-50-gr-1000-round-case

我想提取标题和价格。我最好的尝试只是返回一个空的 []

User-Ps-MacBook-Pro:ammo user$ scrapy shell "http://www.ammofast.com/collections/pistolproducts/aguila-25-auto-acp-full-metal-jacket-50-gr-1000-round-case"
...
>>> response.xpath('//div[@id="product-header-title"]/h1[@id="product-title"]/text()').extract
<bound method SelectorList.extract of []>

我尝试了一些不同的变体,但都无济于事。我想我还没有完全理解 XPath 结构,但这就是我练习的原因:) 感谢您的帮助!我也在使用 Scrapy 1.1.0。

价格是使用Javascript加载的,在源码中可以看到:

window.ShopifyAnalytics.lib.track(
          "Viewed Product",
          {"id":705964349,"name":"Aguila .25 Auto ACP Full Metal Jacket 50 Gr 1000 Round Case - 1000 \/ 50","price":"329.99","currency":"USD","sku":"","brand":"Aguila","category":".25 ACP","nonInteraction":true}
        );

            });

你看返回的source可以看到p class="price"里面其实没有文字:

 <div id="purchase">
                <p class="price"></p>                                 
                <input class="btn" type="submit" name="add" id="add-to-cart" value="Add to Cart" />
              </div>

            </div><!-- /.options -->

您可以做的是解析该功能代码或从选项标签中获取价格:

In [15]: response.xpath("//*[@id='product-title']/text()")
Out[15]: [<Selector xpath="//*[@id='product-title']/text()" data=u'Aguila .25 Auto ACP Full Metal Jacket 50'>]

In [16]: response.xpath("//option/text()")
Out[16]:  [<Selector xpath="//*[@id='product-select']/option/text()" data=u'1000 / 50 - 9.99'>]