【问题标题】:how to choose a complex class?如何选择一个复杂的类?
【发布时间】:2014-02-28 10:52:03
【问题描述】:

请帮助解决问题。

html:

<form class="variants" action="/cart">
    <a class="thumb fancybox image_outer" href="products/apple-iphone-5s-16gb-black--space-gray-chernyj" data-fancybox-group="gallery5">
        <img src="http://first-store.ru/files/products/iphone%205S%20black_1.100x112.jpg?16ef5c4132fc88594851f92ccc2f3437" alt="Apple iPhone 5s 16GB Black &amp; Space Gray (Чёрный)" title="Apple iPhone 5s 16GB Black &amp; Space Gray (Чёрный)">
    </a>

    <h1>
        <a class="name_mark" data-product="1075" href="products/apple-iphone-5s-16gb-black--space-gray-chernyj">Apple iPhone 5s 16GB Black &amp; Space Gray (Чёрный)</a>
    </h1>

    <span class="price price_mark price_value">26 990&nbsp;<span class="currency">руб</span>

        <input id="variants_2927" name="variant" value="2927" type="radio" class="variant_radiobutton" checked="" style="display:none;">

        <input class="button buy buy_button buy_button_catalog" type="submit" value="Купить" data-result-text="Добавлено">
    </span>     
</form>

1 代码无效:

price = article.xpath('span[@class="price"]/span[@class="currency"]/text()')[0].strip()
if price:
    print(price)

2 代码有效:

price = article.xpath('span/span[@class="currency"]/text()')[0].strip()
if price:
    print(price)

但我需要在模型#1上找到一个“价格”。问题是属性类是由几个值组成的。

【问题讨论】:

标签: python xpath python-3.x lxml


【解决方案1】:

[@class="price"] 仅在 class 属性值恰好是 price 时匹配。

您需要类似于以下的 xpath:

price = article.xpath('span[contains(concat(" ", normalize-space(@class), " "), " price ")]/span[@class="currency"]/text()')[0].strip()

也许你最好使用css selector

price = article.cssselect('span.price>span.currency')[0].text.strip()

【讨论】:

    【解决方案2】:

    您可以使用这样的 xpath(只需选择价格范围):

    article.xpath('span[contains(concat(" ", normalize-space(@class), " "), " price ")]')
    

    另一种可能性是使用 css 选择器:

    article.cssselect('span.price')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      相关资源
      最近更新 更多