【发布时间】:2019-12-05 11:43:28
【问题描述】:
函数不会抛出任何错误,但字符串在执行后保持不变。看起来replace_with 什么都不做。所以我检查了 var 的类型,我认为这是问题所在:
<class 'str'> <class 'bs4.element.Tag'>
fixed_text 是 str 和 blog_text 是 tag 类型。我不知道如何解决这个问题。
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)
【问题讨论】:
-
你是如何检查字符串没有被改变的?文件本身不会改变。
-
当我的
print(fixed_text)字符串改变了,当print(blog_text)还是一样。我还检查了手册 index.html。在fixed_text和fixed_text_2下是存储新的、想要的值。只有replace_with_不起作用。那么我如何能够在同一个 .html 文件中更改和保护这个新字符串呢?
标签: python django beautifulsoup