【问题标题】:BeautifulSoup won't replace stringBeautifulSoup 不会替换字符串
【发布时间】:2019-12-05 11:43:28
【问题描述】:

函数不会抛出任何错误,但字符串在执行后保持不变。看起来replace_with 什么都不做。所以我检查了 var 的类型,我认为这是问题所在:

<class 'str'> <class 'bs4.element.Tag'>

fixed_textstrblog_texttag 类型。我不知道如何解决这个问题。

    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_textfixed_text_2 下是存储新的、想要的值。只有replace_with_ 不起作用。那么我如何能够在同一个 .html 文件中更改和保护这个新字符串呢?

标签: python django beautifulsoup


【解决方案1】:

您的解决方案似乎运行良好。但是,据我所知,您尝试做的是将整个 href 替换为另一个。最简单的方法是:

blog_text.attrs['href'] = replace_string_1

这将改变元素inside 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'))  

【讨论】:

  • 谢谢。有用。但是现在我不知道如何在 .html 文件中替换和保存新字符串?不替换整个 .html 文件,只需将其放在必须的位置即可。
  • 好吧,恐怕你需要替换整个内容。查看更新的答案。
  • 现在的问题是文件 (f) 已经打开了。所以我试着保存,我看到了:f.write(soup.prettify('utf-8')) TypeError: write() argument must be str, not bytes
  • 这是因为你需要以字节模式打开它,使用"b"。为什么不以读取模式打开,关闭然后以写入模式打开?但这些是与文件处理相关的其他问题,而不是美丽的汤。我们应该将此问题标记为已解决吗?
猜你喜欢
  • 1970-01-01
  • 2012-09-25
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多