2017-02-23 235 views
0

Есть ли способ удалить все теги html из строки, но оставить некоторые ссылки и изменить их представление? Пример:Python - Строка из тегов html, оставлять ссылки, но в измененной форме

description: <p>Animation params. For other animations, see <a href="#myA.animation">myA.animation</a> and the animation parameter under the API methods.  The following properties are supported:</p> 
<dl> 
    <dt>duration</dt> 
    <dd>The duration of the animation in milliseconds.</dd> 
<dt>easing</dt> 
<dd>A string reference to an easing function set on the <code>Math</code> object. See <a href="http://example.com">demo</a>.</dd> 
</dl> 
<p> 

и я хочу, чтобы заменить

<a href="#myA.animation">myA.animation</a> 

только 'myA.animation', но

<a href="http://example.com">demo</a> 

с 'демо: http://example.com'

EDIT: Сейчас, похоже, работает:

def cleanComment(comment): 
    soup = BeautifulSoup(comment, 'html.parser') 
    for m in soup.find_all('a'): 
     if str(m) in comment: 
      if not m['href'].startswith("#"): 
       comment = comment.replace(str(m), m['href'] + " : " + m.__dict__['next_element']) 
    soup = BeautifulSoup(comment, 'html.parser') 
    comment = soup.get_text() 
    return comment 
+0

Ваши примеры глобальные правила для вас html? Или может быть, что некоторые ссылки вы хотите сохранить, а другие нет? – arieljannai

+0

Да, есть только два типа ссылок. – Ratka

ответ

0

Это регулярное выражение должно работать для вас: (?=href="http)(?=(?=.*?">(.*?)<)(?=.*?"(https?:\/\/.*?)"))|"#(.*?)"

Вы можете попробовать это over here

В Python:

import re 

text = '' 
with open('textfile', 'r') as file: 
    text = file.read() 

matches = re.findall('(?=href="http)(?=(?=.*?">(.*?)<)(?=.*?"(https?:\/\/.*?)"))|"#(.*?)"', text) 

strings = [] 
for m in matches: 
    m = filter(bool, m) 
    strings.append(': '.join(m)) 

print(strings) 

Результат будет выглядеть так: ['myA.animation', 'demo: http://example.com']

+0

Wooaa, я даже не знаю, как начать с него в коде – Ratka

+0

Я добавил пример python для вас – arieljannai

+0

Спасибо, но я нашел решение, которое, кажется, работает для меня – Ratka

Смежные вопросы