【发布时间】: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