【问题标题】:How to get data from span tag which have custom characteristics? (BeautifulSoup)如何从具有自定义特征的 span 标签中获取数据? (美人汤)
【发布时间】:2020-11-05 23:33:45
【问题描述】:

我有以下 span 标签。怎么刮xuRMlBoIUcI7nAJktBcJvPByp1DLE4aPGzq3JNiRKsdNqUkVSJBY%2BggxRhp0GcRx4Gw4lWQxbTk%3D 哪个分配给 data-slug?

    <span data-ju-jspjrvxy="" 
    data-slug="xuRMlBoIUcI7nAJktBcJvPByp1DLE4aPGzq3JNiRKsdNqUkVSJBY%2BggxRhp0GcRx4Gw4lWQxbTk%3D" 
    data-gtm-clickedelement="CTA button" data-gtm-offer="" data-ju-wvxjoly-pk="303795"
 data-gtm-voucher-id="303795" class="businessinsiderus-voucher-button-holder clear">

        

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    如果我对您的问题的理解是正确的,您想抓取标签的属性。 如果这实际上是您的问题,以下链接将提供解决方案: Extracting an attribute value with beautifulsoup

    【讨论】:

      【解决方案2】:

      如果s 是您的数据字符串,则使用正则表达式模块:

      import re
      match = re.findall('data\-slug=\"()\"',str(s))
      

      【讨论】:

      • 我希望将完整的字符串分配给 data-slug。
      • 是的,这将返回所有可能匹配的字符串数组。如果只需要一个字符串,则 match[0]
      • 我有多个 span 标签,每个标签都有一个唯一的值分配给 data-slug。它也可以解决这个问题。
      • 是的,它会返回多个字符串中的一个。在输入字符串 s 中包含多个 data-slugs
      • 在findall函数中最好使用str(s),我已经编辑了答案。
      【解决方案3】:
          from bs4 import BeautifulSoup as BS
      
          content = 'your html span text here'
      
          soup = BS(content,parser='html', features='lxml')
      
          dict_of_spantag_attributes_and_values = soup.span.attrs
      
          for i,j in dict_of_spantag_attributes_and_values.items():
      
              print(f'{i}:{j}')
      

      【讨论】:

        猜你喜欢
        • 2015-11-17
        • 2021-05-22
        • 1970-01-01
        • 2019-07-30
        • 2014-10-16
        • 1970-01-01
        • 1970-01-01
        • 2020-07-16
        • 1970-01-01
        相关资源
        最近更新 更多