【发布时间】: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