我试图阻止BeautifulSoup在下一个标记包含文本“Utility”时添加换行符。你知道吗
<html>
<dl>
<dt>RandomText</dt> <!-- Line Break -->
<dt>RandomText</dt> <!-- Don't insert Line Break -->
<dt>Utility: NonStaticText</dt> <!-- Line Break -->
</dl>
</html>
现在我有:
soup.unwrap('head')
for dt in soup.findAll('dt'):
dt.insert_after('\n')
这是非常小的,但我该怎么办呢?文本“Utility:”经常出现,但“Utility:”之后的内容在每种情况下都是不同的,并且包含在标记中。我用的是BS4。你知道吗
更新:
我发现:
for dt in soup.find_all('dt'):
if not dt.find(string = re.compile('Utility')):
dt.insert_before('\n')
似乎有点管用。我真正需要的是评估树中的下一个标记,并评估它是否具有字符串“Utility”,然后根据该字符串做出决定。理想的。。。你知道吗
dt.insert_before('n')
应该是:
dt.insert_after('n')
更新2:
这就是我的解决方案:
for dt in soup.find_all('dt'):
next_tag = dt.find_next('dt')
try: # THROWS 'AttributeError' IF NOT FOUND ...
if not next_tag.text.startswith('Utility'):
dt.insert_after('\n')
except AttributeError as e:
pass
可以使用^{} 方法获取下一个标记,例如:
请注意,如果在
find_next
中不传递任何参数,它将匹配后面的任何标记。你知道吗相关问题 更多 >
编程相关推荐