【问题标题】:How to get style tag content with xpath如何使用 xpath 获取样式标签内容
【发布时间】:2016-02-18 21:54:17
【问题描述】:

我必须在 python 中使用 xpath 分析以下 html-content。我必须得到的内容是style-tag的内容。

<div class="chartBody">
    <div class="chartRow">
        <div class="chartLabel">Certificate</div>
            <div class="chartBar_g" style="width:300px">&nbsp;</div>
    </div>
    <div class="chartRow">
        <div class="chartLabel">Protocol Support</div>
            <div class="chartBar_a" style="width:210px">&nbsp;</div>
    </div>
</div>

包含样式标签的类不同。 每个人都可以告诉我 xpath 字符串,以获取列表中的所有样式内容吗?

【问题讨论】:

  • 您真的只限于使用 xpath,您受限于哪些工具?使用 Beautiful Soup 或 Selenium 的任务相对简单,但同样我们需要了解更多信息才能选择正确的工具

标签: python html xpath lxml


【解决方案1】:

enter code here1) 搜索具有style 属性的元素,例如:

element = driver.find_element_by_class("chartBar_g")

2) 获取样式属性:

element.get_attribute("style")

您可以通过以下方式获取具有样式属性的“所有”div 元素

elements = driver.find_elements_by_xpath("//div[@style]")

然后您可以遍历元素并应用我在第 2 步中描述的内容

【讨论】:

    【解决方案2】:
    import html5lib
    
    str = yourHtml
    html_parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("lxml"), namespaceHTMLElements=False)
    page = html_parser.parse(str, encoding="utf-8")
    page.xpath("//div[@class = 'chartBar_g']//@style")
    

    输出是: ['宽度:30px']

    【讨论】:

      猜你喜欢
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多