我有一个 HTML 文档,其中包含一堆<div>
的,带着孩子<p>
的和里面<href>
的。目标是这样的,
- 去除
<div>
and <p>
tags
- 在每个删除的末尾
<div>
add a </br>
Example
这样:
<div>
<p>
<a href="" id="tnt1">[1]</a>"RFC 4456 - BGP Route Reflection: An Alternative to Full ... - IETF Tools.">ref="https://example.com">https://https://example.com"</a></span><span>. Accessed 15 Nov. 2017.
</p>
</div>
就变成这样了:
<a href="" id="tnt1">[1]</a>"RFC 4456 - BGP Route Reflection: An Alternative to Full ... - IETF Tools.">ref="https://example.com">https://https://example.com"</a></span><span>. Accessed 15 Nov. 2017.
</br>
Current
到目前为止我的代码是:
from bs4 import BeautifulSoup
for div in soup.find_all(name=re.compile(r'div')):
print div
然而,所有示例似乎都指向替换内部文本而不是实际标签。另外,如果有办法在 bs3 中做到这一点,那将是理想的,因为我所有其他代码当前都使用 v3。
有人能指出我正确的方向吗?谢谢,
''.join(str(x) for x in div.p.contents)
给我内部 HTML 作为 bs4 上的字符串
I get parent = div.parent
稍后使用它
Using div.extract()
我删除div
与所有子标签。
Using parent.append()
我把内部 HTML 放回去了。
from bs4 import BeautifulSoup
data = '''<strong>
<div>
<p>
<a href="" id="tnt1">[1]</a>"RFC 4456 - BGP Route Reflection: An Alternative to Full ... - IETF Tools.">ref="https://example.com">https://https://example.com"</a></span><span>. Accessed 15 Nov. 2017.
</p>
</div>
</strong>'''
soup = BeautifulSoup(data, 'html.parser')
for div in soup.find_all('div'):
parent = div.parent
inner = ''.join(str(x) for x in div.p.contents) + "<br/>"
print('--- inner ---')
print(inner)
# remove div with all subtags
div.extract()
parent.append(BeautifulSoup(inner, 'html.parser'))
print('--- after ---')
print(parent)
Result:
--- inner ---
<a href="" id="tnt1">[1]</a>"RFC 4456 - BGP Route Reflection: An Alternative to Full ... - IETF Tools.">ref="https://example.com">https://https://example.com"<br/>
--- after ---
<strong>
<a href="" id="tnt1">[1]</a>"RFC 4456 - BGP Route Reflection: An Alternative to Full ... - IETF Tools.">ref="https://example.com">https://https://example.com"<br/></strong>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)