#Python BeautifulSoup 教程
假设要将所有值htttps://xxx.com 的 href 属性的值,替换为 htttps://zzz.com 。
htttps://xxx.com
htttps://zzz.com
from bs4 import BeautifulSoup html_content = ''' <a href="https://xxx.com">测试01</a> <a href="https://yyy.com/123">测试02</a> ''' soup = BeautifulSoup(html_content, 'html.parser') for element in soup.find_all('a'): if 'href' in element.attrs: if element.attrs['href'] == 'https://xxx.com': element.attrs['href'] = 'https://zzz.com' print(soup)
执行结果:
<a href="https://zzz.com">测试01</a> <a href="https://yyy.com/123">测试02</a>
( 本文完 )