2016-08-01 55 views
0

試圖實現以下邏輯:錨(<a href="URL">URL</a>)代替文本(<p>URL</p>)

如果URL在文本由段落標記(例如:<p>URL</p>)包圍,取代它到位成爲鏈路,而不是:<a href="URL">Click Here</a>

原始文件是數據庫轉儲(sql,UTF-8)。某些網址已經以所需的格式存在。我需要修復缺失的鏈接。

我正在使用一個腳本,它使用Beautifulsoup。如果其他解決方案更有意義(正則表達式等),我願意接受建議。

+0

請提供你已經做了一些例子,說明你遇到的任何問題。 – Will

回答

0

您可以搜索文本以http開頭的所有p元素。然後,replace it with鏈接:

for elm in soup.find_all("p", text=lambda text: text and text.startswith("http")): 
    elm.replace_with(soup.new_tag("a", href=elm.get_text())) 

示例工作代碼:

from bs4 import BeautifulSoup 

data = """ 
<div> 
    <p>http://google.com</p> 
    <p>https://stackoverflow.com</p> 
</div> 
""" 

soup = BeautifulSoup(data, "html.parser") 
for elm in soup.find_all("p", text=lambda text: text and text.startswith("http")): 
    elm.replace_with(soup.new_tag("a", href=elm.get_text())) 

print(soup.prettify()) 

打印:

<div> 
    <a href="http://google.com"></a> 
    <a href="https://stackoverflow.com"></a> 
</div> 

我能想象這種做法決裂,但它應該是一個良好的開端爲您服務。


如果您還想要文本添加到您的鏈接,設置.string屬性:

soup = BeautifulSoup(data, "html.parser") 
for elm in soup.find_all("p", text=lambda text: text and text.startswith("http")): 
    a = soup.new_tag("a", href=elm.get_text()) 
    a.string = "link" 
    elm.replace_with(a) 
+0

亞歷山大,感謝您的及時迴應。我測試了你的解決方案。它工作得很好。如果你不介意,還有一個更快的問題。我如何用靜態文本裝飾錨點,使它們不顯示爲空?例如,href =「http://google.com>點擊這裏而不是隻是空標籤? – bytebybyte

+0

@bytebybyte肯定,更新了答案。很高興爲您提供幫助。 – alecxe