2016-08-01 56 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