簡體   English   中英

解析前從HTML去除空格

[英]Strip white-space from HTML before parsing

我有一個包含HTML的Python字典,稍后我想使用beautifulsoup進行解析,但是在解析之前,我想刪除與標簽元素直接相鄰的空格。

例如:

string = "text <tag>some texts</tag> <tag> text</tag> some text"
>>> remove_whitespace(string)
'text<tag>some texts</tag><tag>text</tag>some text'

假設您允許使用任何種類的標簽名稱,並且標簽中絕不包含尖括號,則可以使用正則表達式快速解決此問題:

>>> import re
>>> string = "text <tag>some texts</tag> <tag> text</tag> some text"
>>> regex = re.compile(r"\s*(<[^<>]+>)\s*")
>>> regex.sub("\g<1>", string)
'text<tag>some texts</tag><tag>text</tag>some text'

說明:

\s*     # Match any number of whitespace characters
(       # Match and capture in group 1:
 <      # - an opening angle bracket
 [^<>]+ # - one or more characters except angle brackets
 >      # - a closing angle bracket
)       # End of group 1 (used to restore the matched text later)
\s*     # Match any number of whitespace characters

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM