【问题标题】:Get attribute values by BeautifulSoup通过 BeautifulSoup 获取属性值
【发布时间】:2015-08-28 12:33:36
【问题描述】:

我想从 BeautifulSoup 的内容中获取所有 data-js 属性值。

输入:

<p data-js="1, 2, 3">some text..</p><p data-js="5">some 1 text</p><p data-js="4"> some 2 text. </p>

输出:

['1, 2, 3', '5', '4']

我已经用 lxml 完成了:

>>> content = """<p data-js="1, 2, 3">some text..</p><p data-js="5">some 1 text</p><p data-js="4"> some 2 text. </p>"""
>>> import lxml.html as PARSER
>>> root = PARSER.fromstring(content)
>>> root.xpath("//*/@data-js")
['1, 2, 3', '5', '4']

我想要通过 BeautifulSoup 获得上述结果。

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    这个想法是找到所有具有data-js attributes 的元素并将它们收集到一个列表中:

    from bs4 import BeautifulSoup
    
    
    data = """
    <p data-js="1, 2, 3">some text..</p><p data-js="5">some 1 text</p><p data-js="4"> some 2 text. </p>
    """
    
    soup = BeautifulSoup(data)
    print [elm['data-js'] for elm in soup.find_all(attrs={"data-js": True})]
    

    打印['1, 2, 3', '5', '4']

    【讨论】:

      【解决方案2】:

      使用map 可能是一种更快的方法,无需列表理解。

      from bs4 import BeautifulSoup
      d = "..."
      # create a soup instance
      soup = BeautifulSoup(d)
      # find all p-elements containing an data-js attribute
      p = soup.find_all('p', attrs={"data-js": True})
      # unpack data-js attribute from p-elements and map to new list
      print map(lambda x: x['data-js'], p)
      

      http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all

      【讨论】:

      • 谢谢。赞成,data-js 属性将是任何标签。
      • @VivekSable 我知道,True 只是保证密钥 data-js 存在于 p 元素中。所以你不会遇到KeyError: 'data-js'
      【解决方案3】:

      你可以使用 find_all() 来做这个,但是你必须把属性名放在字典里,因为它本身不能用作关键字参数。

      html = BeautifulSoup(content)
      data = html.find_all(attrs={'data-js': True})
      

      更多解释请见here

      【讨论】:

        猜你喜欢
        • 2016-09-19
        • 2018-11-05
        • 2013-09-14
        • 1970-01-01
        • 2016-02-25
        • 2012-11-17
        • 1970-01-01
        • 1970-01-01
        • 2010-12-13
        相关资源
        最近更新 更多