【问题标题】:Python + BeautifulSoup: Finding a HTML tag where an attribute contains a matched pattern of text?Python + BeautifulSoup:查找属性包含匹配文本模式的 HTML 标记?
【发布时间】:2018-11-15 23:43:50
【问题描述】:

我是 Python 和 BeautifulSoup 的新手。我试图弄清楚如何仅匹配 <div> 元素的标签,这些标签包含属于某个属性的特定匹配文本模式。例如,'id' : 'testid' 的所有情况,或'class' : 'title' 的所有情况。

这是我目前所拥有的:

def cleanup(filename):
    fh = open(filename, "r")

    soup = BeautifulSoup(fh, 'html.parser')

    for div_tag in soup.find('div', {'class':'title'}):
        h2_tag = soup.h2_tag("h2")
        div_tag.div.replace_with(h2_tag)
        del div_tag['class']

    f = open("/tmp/filename.modified", "w")
    f.write(soup.prettify(formatter="html5"))
    f.close()

一旦我可以匹配所有这些特定元素,我就可以弄清楚如何操作属性(删除类,将标签本身从 <div> 重命名为 <h1> 等)。所以我知道清理的实际部分可能不适用于目前的情况。

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    这似乎足够有效,但如果有“更好”或“更标准”的方法可以让我知道。

    for tag in soup.findAll(attrs={'class':'title'}):
        del tag['class']
    

    【讨论】:

      【解决方案2】:

      .find(tagName, attributes) 返回单个元素

      .find_all(tagName, attributes)返回多个元素(列表)

      更多您可以在doc找到它

      要替换,您需要创建元素 .new_tag(tagName) 并删除属性 del element.attrs[attributeName] 参见下面的示例

      from bs4 import BeautifulSoup
      import requests
      
      html = '''
      <div id="title" class="testTitle">
        heading h1
      </div>
      '''
      soup = BeautifulSoup(html)
      
      print 'html before'
      print soup
      
      div = soup.find('div', id="title")
      
      #delete class attribute
      del div.attrs['class']
      
      print 'html after remove attibute'
      print soup
      
      # to replace, create h1 element
      h1 = soup.new_tag("h1")
      # set text from previous element
      h1.string = div.text
      # uncomment to set ID
      # h1['id'] = div['id']
      div.replace_with(h1)
      
      print 'html after replace'
      print soup
      

      【讨论】:

        猜你喜欢
        • 2017-01-24
        • 2010-10-26
        • 2018-02-11
        • 1970-01-01
        • 1970-01-01
        • 2010-09-28
        • 2011-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多