【问题标题】:struggling on xpath establishment在 xpath 建立上苦苦挣扎
【发布时间】:2014-05-11 11:48:36
【问题描述】:

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

http://tinyurl.com/lzw44mn

我要抓取的项目分别是所有智能手机的品牌、型号和价格,如图所示:

但是,我正在努力建立有效的主 xpath。尝试测试了几个xpath,以这个结束:

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

但没有成功。

对此有任何提示吗?

【问题讨论】:

    标签: xml python-2.7 xpath scrapy


    【解决方案1】:

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

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

    价格可以查看id属性:

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

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

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


    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...'}
    ...
    

    【讨论】:

    • 感谢您的回复。 (.//div[@class="m_product_title_div"]/text()) 返回空字符串。
    • @user3404005 你能显示你的蜘蛛的相关代码吗?这样我就可以调试问题了。仅供参考,xpaths 在 chrome 控制台中工作。
    • 还没有构建蜘蛛(虽然我之前已经构建了几个),因为主要的 xpath 问题。
    • @user3404005 我已经编写了蜘蛛 - 检查 UPD 部分。
    • 这是一部杰作。非常感谢!
    【解决方案2】:

    使用 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 中这样做。

    【讨论】:

    • 谢谢。 sel.xpath('//div[@class="m_product_preview_div"]').extract() 在终端测试时返回空搅拌。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多