python - BeautifulSoup 不会替换字符串
问题描述
函数不会抛出任何错误,但字符串在执行后保持不变。看起来replace_with
什么都不做。所以我检查了 var 的类型,我认为这是问题所在:
<class 'str'> <class 'bs4.element.Tag'>
fixed_text
isstr
和blog_text
istag
类型。我不知道如何解决这个问题。
def replace_urls(self):
find_string_1 = '/blog/'
find_string_2 = '/contakt/'
replace_string_1 = 'blog.html'
replace_string_2 = 'contact.html'
exclude_dirs = ['media', 'static']
for (root_path, dirs, files) in os.walk(f'{settings.BASE_DIR}/static/'):
dirs[:] = [d for d in dirs if d not in exclude_dirs]
for file in files:
get_file = os.path.join(root_path, file)
f = open(get_file, mode='r', encoding='utf-8')
soup = BeautifulSoup(f, "lxml", from_encoding="utf-8")
blog_text = soup.find('a', attrs={'href':find_string_1})
contact_text = soup.find('a', attrs={'href':find_string_2})
fixed_text = str(blog_text).replace(find_string_1, replace_string_1)
fixed_text_2 = str(contact_text).replace(find_string_2, replace_string_2)
blog_text.replace_with(fixed_text)
contact_text.replace_with(fixed_text_2)
解决方案
您的解决方案似乎完美无缺。但是,据我所知,您尝试做的是将整个替换为href
另一个。最简单的方法是:
blog_text.attrs['href'] = replace_string_1
这将改变里面 的元素soup
,所以最后你可以这样做:
str(soup)
并查看您的更改。通过这样做str(blog_text).replace
,您正在处理与汤分离的字符串。
最小的例子:
find_string_1 = '/blog/'
replace_string_1 = 'blog.html'
from bs4 import BeautifulSoup
soup = BeautifulSoup('<a href="/blog/">the text</a>', "lxml")
blog_text = soup.find('a', attrs={'href':find_string_1})
blog_text.attrs['href'] = replace_string_1
print(str(soup))
结果:
'<html><body><a href="blog.html">the text</a></body></html>'
编辑:将更改写回文件:
with open(some_file_name, 'wb') as f_out:
f_out.write(soup.prettify('utf-8'))