【问题标题】:How to select specific HTML hypertext markup on Python with html.xpath如何使用 html.xpath 在 Python 上选择特定的 HTML 超文本标记
【发布时间】:2020-12-18 03:04:49
【问题描述】:

在抓取网站内容时,我遇到了一个问题,促销价格被交叉并替换为另一个价格(使用<del><ins> html 超文本标记)。

这里是我尝试使用的那一点的 HTML 源代码:

<span class="price"><del>
<span class="woocommerce-Price-amount amount">
<bdi>49,00&nbsp;<span class="woocommerce-Price-currencySymbol">MAD</span>
</bdi></span></del> 
<ins><span class="woocommerce-Price-amount amount"><bdi>35,00&nbsp;<span class="woocommerce-Price-currencySymbol">MAD</span></bdi></span></ins></span>

我正在尝试仅选择 &lt;ins&gt; 中的部分。

到目前为止,我已使用此代码提取价格,但它不区分交叉价格和实际价格。

sourceCode.xpath('//span[@class="price"]/descendant::node()/text()')

我不知道如何只选择&lt;ins&gt; 部分。

【问题讨论】:

    标签: python html xpath web-scraping


    【解决方案1】:

    在提取价格值之前,我们实际上遵循&lt;del&gt; 的含义概念remove del elements 怎么样:

    In [1]: from lxml import html
    
    In [2]: data = """<span class="price"><del>
       ...: <span class="woocommerce-Price-amount amount">
       ...: <bdi>49,00&nbsp;<span class="woocommerce-Price-currencySymbol">MAD</span>
       ...: </bdi></span></del> 
       ...: <ins><span class="woocommerce-Price-amount amount"><bdi>35,00&nbsp;<span class="woocommerce-Price-currencySymbol">MAD</span></bdi></span></ins></span>"""
    
    In [3]: root = html.fromstring(data)
    
    In [4]: for del_element in root.xpath('//span[@class="price"]//del'): 
                del_element.getparent().remove(del_element)
    
    In [5]: root.xpath('//span[@class="price"]/descendant::node()/text()')
    Out[5]: ['35,00\xa0', 'MAD']
    

    我认为这可能比尝试编写 XPath 表达式来处理既有旧价格又有新价格或只有一个价格的情况更好。

    【讨论】:

      猜你喜欢
      • 2013-03-23
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 2021-12-31
      相关资源
      最近更新 更多