在xpath建立上挣扎

时间:2014-03-31 22:27:52

标签: xml python-2.7 xpath scrapy

我正在尝试为此页面建立xpath:

http://tinyurl.com/lzw44mn

我想要抓取的商品分别是所有智能手机的品牌,型号名称和价格,如照片所示:

enter image description here

然而,我正努力建立有效的主xpath。试图测试几个xpath,完成这个:

sel.xpath('//div[@style="position: relative;"]').extract()

但没有成功。

有关此的任何提示吗?

2 个答案:

答案 0 :(得分:2)

对于品牌和型号名称,请使用class属性名称:

//div[@class="m_product_title_div"]/text()

价格方面,您可以查看id属性:

//div[@id="m_product_price_div"]/text()

在chrome控制台中测试这些xpath表达式(使用$x('xpath_here')语法)。

您可能需要相对于手机特定的块(.//div[@class="m_product_title_div"]/text())和strip()前导和尾随空格和换行符创建这些xpath表达式。


UPD(抓住品牌,头衔和价格的蜘蛛):

from scrapy.item import Item, Field
from scrapy.spider import BaseSpider
from scrapy.selector import Selector


class MobiItem(Item):
    brand = Field()
    title = Field()
    price = Field()


class MobiSpider(BaseSpider):
    name = "mobi"
    allowed_domains = ["mobi.ge"]
    start_urls = [
        "http://mobi.ge/?page=products&category=60"
    ]

    def parse(self, response):
        sel = Selector(response)
        blocks = sel.xpath('//table[@class="m_product_previews"]/tr/td/a')
        for block in blocks:
            item = MobiItem()
            try:
                item["brand"] = block.xpath(".//div[@class='m_product_title_div']/span/text()").extract()[0].strip()
                item["title"] = block.xpath(".//div[@class='m_product_title_div']/span/following-sibling::text()").extract()[0].strip()
                item["price"] = block.xpath(".//div[@id='m_product_price_div']/text()").extract()[0].strip()
                yield item
            except:
                continue

抓取:

{'brand': u'Samsung', 'price': u'695 GEL', 'title': u'G7102 Grand dous 2'}
{'brand': u'Samsung', 'price': u'572 GEL', 'title': u'I9060 Galaxy grand...'}
...

答案 1 :(得分:0)

使用XPath表达式//div[@class="m_product_preview_div]选择所有产品。现在循环遍历它,每次从上面提取的产品的上下文中运行那些XPath查询:

  • ./div[@class="m_product_title_div"]/span[@class="like_link"]/text()供应商(鉴于它已链接)
  • 产品名称
  • ./div[@class="m_product_title_div"]/text()
  • ./div[@id="m_product_price_div"]/text()的价格

之后你会非常喜欢修剪空白。虽然这可以使用XPath和normalize-space(...),但我可能会在Python中这样做。

相关问题