簡體   English   中英

Python 查找和更換美湯

[英]Python Find & Replace Beautiful Soup

我正在使用 Beautiful Soup 將出現的模式替換為 HTML 文件中的 href 鏈接

我面臨如下所述的問題

modified_contents = re.sub("([^http://*/s]APP[a-z]{2}[0-9]{2})", "<a href=\"http://stack.com=\\1\">\\1</a>", str(soup))

樣本輸入 1:

Input File contains APPdd34

Output File contains <a href="http://stack.com=APPdd34"> APPdd34</a>

樣本輸入 2:

Input File contains <a href="http://stack.com=APPdd34"> APPdd34</a>

Output File contains <a href="http://stack.com=<a href="http://stack.com=APPdd34"> APPdd34</a>"> <a href="http://stack.com=APPdd34"> APPdd34</a></a>

所需的 Output 文件 2 與示例輸入文件 2 相同。

我該如何解決這個問題?

這可能無法完全回答您的問題,因為我不知道整個輸入文件可能是什么樣子,但我希望這是您可以采取的方向。

from BeautifulSoup import BeautifulSoup, Tag
text = """APPdd34"""
soup = BeautifulSoup(text)
var1 = soup.text
text = """&lt;a href="http://stack.com=APPdd34"&gt; APPdd34&lt;/a&gt;"""
soup = BeautifulSoup(text)
var2 = soup.find('a').text

soup = BeautifulSoup("&lt;p>Some new html&lt;/p&gt;")
tag1 = Tag(soup, "a",{'href':'http://stack.com='+var1,})
tag1.insert(0,var1) # Insert text
tag2 = Tag(soup, "a",{'href':'http://stack.com='+var2,})
tag2.insert(0,var2)
soup.insert(0,tag1)
soup.insert(3,tag2)
print soup.prettify()

所以基本上,只需使用 BeautifulSoup 來提取文本,然后您就可以從那里構建標簽。

暫無
暫無

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

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