【问题标题】:BeautifulSoup: Saving changes back to HTMLBeautifulSoup:将更改保存回 HTML
【发布时间】:2018-07-21 08:55:56
【问题描述】:

我有以下 Python 代码:

content = webpage.content
soup = Soup(content, 'html.parser')
app_url = scheme + app_identity.get_default_version_hostname() + '/'

for link in soup.find_all(href = True):
    if scheme in link['href']:
        link['href'] = link['href'].replace(scheme, app_url)
        logging.info('@MirrorPage | Updated link: %s', link['href'])
    else:
        link['href'] = input_url + link['href'].strip('/')
        logging.info('@MirrorPage | Updated asset: %s', link['href'])

# https://stackoverflow.com/questions/15455148/find-after-replacewith-doesnt-work-using-beautifulsoup/19612218#19612218
#soup = Soup(soup.renderContents())

# https://stackoverflow.com/questions/14369447/how-to-save-back-changes-made-to-a-html-file-using-beautifulsoup-in-python
content = soup.prettify(soup.original_encoding)

并像这样渲染我的 HTML:

self.response.write(Environment().from_string(unicode(content, errors = 'ignore')).render())

app_identity 来自 Google App Engine,jinja2 用于模板/渲染。我已经尽我所能将修改后的 HTML 写回content 变量,以便呈现正确的网页。如何正确写出我所做的任何更改?我曾尝试在适当的情况下使用replaceWith,但这似乎不起作用。我做错了什么?

【问题讨论】:

    标签: python html python-2.7 google-app-engine beautifulsoup


    【解决方案1】:

    此函数利用保存html并根据需要将其返回以进行重新处理..

    我在 stackoverflow 上对其进行了测试,它使用替换的链接/方案保存了 html。

    我使用{{description}}作为template.html中的占位符

    它将打开的 html 作为变量返回,然后传回 bs4 对象并打印。

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import codecs
    from xml.sax.saxutils import escape
    import os
    
    import jinja2
    import requests
    from bs4 import BeautifulSoup as bs4
    
    
    def revise_links():
        url = 'https://stackoverflow.com/'
        template_name = 'template.html'
        file_name = 'replaced'
    
        scheme = 'stackoverflow'
        replace_with = 'mysite'
    
        r = requests.get(url)
        html_bytes = r.text
        soup = bs4(html_bytes, 'lxml')
    
        description_source = soup.findAll()
    
        for a in soup.findAll(href=True):
            if scheme in a['href']:
                a['href'] = a['href'].replace(scheme, replace_with)
                print a['href']
            else:
                a['href'] = url + a['href'].strip('/')
    
        # RENDER THE NEW HTML FILE    *
    
        def render(tpl_path, context):
            """Render html file with new data. Looks for the file in the current path"""
            (path, filename) = os.path.split(tpl_path)
        return jinja2.Environment(loader=jinja2.FileSystemLoader(path or './')).get_template(filename).render(context)
    
        # HTML DATA
    
        context = {'description': description_source}
    
        # Render the result
    
        result = render(template_name, context)
    
        # open the html
    
        # with open(file_name + '.html', 'a', encoding='utf-8') as f:
        #      f.write(result)  # write result
    
        # OPEN THE NEW HTML FILE READY TO REVISE **********************
    
        #  f1 = open(file_name + '.html', 'r', encoding='utf-8')
         # descript = f1.read()
    
        return result
    
    
    content = revise_links()
    soup = bs4(content, 'lxml')
    print soup
    

    【讨论】:

    • 根据 BeautifulSoup 文档,您不需要指定标签:crummy.com/software/BeautifulSoup/bs4/doc/#searching-the-tree
    • with open('mirror.html', 'a') as f: IOError: [Errno 30] Read-only file system: 'mirror.html'
    • 无论您在哪里尝试创建文件,都需要写入权限。如果使用谷歌应用引擎。请参见此处并使用谷歌代码修改函数以进行读写...... cloud.google.com/appengine/docs/standard/python/…
    • 正如我在您之前删除的帖子中所说的,这就是我一直在看的内容。在我当前的环境中,cloudstorage 无法使用。
    • 您使用的系统。你没有写权限?只能保存在内存中?
    【解决方案2】:

    在 Google App Project 的 IMAP 首选项下更改服务帐户的权限,修复了写入更改。但是,基本 HTML 并没有呈现整个页面,即在呈现像 Google 这样的网站时,Javascript 和样式似乎不起作用。我可以简单地使用 self.response.write(soup) 渲染 HTML,但这并不能解决这个问题。我将在一个单独的问题中解决这个问题,因为它涉及实际检索(或抓取)指定的网站。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 2012-03-12
      • 2021-12-29
      • 1970-01-01
      • 2012-12-31
      • 2019-10-19
      • 2016-08-07
      相关资源
      最近更新 更多