【问题标题】:how to download and modify a complete webpage? [closed]如何下载和修改一个完整的网页? [关闭]
【发布时间】:2021-11-03 02:11:10
【问题描述】:

我想下载世界上最有趣的笑话的维基百科页面https://en.wikipedia.org/wiki/World%27s_funniest_joke

然后,我想用单词apple 替换所有出现的单词joke(是的,确实更有趣)。

关键是我希望能够单击输出html 文件(用苹果而不是笑话)并能够在我的浏览器中看到与原始网页相同的图像、css 和输出.

  • 我尝试使用 chrome 下载 mhtml 文件并使用 f.read() 修改文件,但文件看起来像二进制数据。

  • 通过(BeautifulSoup(requests.get(myurl), 'html.parser')) 使用requestsbeautifulsoup 只会给我原始的html 而没有格式化。

我能做什么?我不介意一些手动步骤(例如,先在某处下载文件)。

谢谢!

【问题讨论】:

  • 我认为你需要一两门现代网页设计的基础课程。
  • 谢谢,这是一个有用的评论。你有可能的解决方案吗?

标签: python selenium beautifulsoup python-requests


【解决方案1】:

我以mhtml 下载了维基百科页面,并且能够将单词joke(s) 的每个实例替换为apple(s)。这是我用来替换目标字符串的代码。

#! python
import os
import sys
import fileinput

# Read in the file
with open("World's funniest joke - Wikipedia.mhtml", 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('joke', 'apple')
filedata = filedata.replace('jokes', 'apples')
filedata = filedata.replace('Joke', 'Apple')
filedata = filedata.replace('Jokes', 'Apples')

# Write the file out again
with open("World's funniest joke - Wikipedia.mhtml", 'w') as file:
  file.write(filedata)

编辑: 添加了疯狂物理学家的建议,将所有笑话替换为苹果。

谢谢!

【讨论】:

  • 谢谢!当您打开修改后的 mhtml 文件时,您是否仍然看到与原始页面相同的格式(颜色等?)
  • 你没有替换JokeJokes(大写J
  • 是的,您仍然看到这些字词是蓝色的或超链接的。如果您在我的回复中单击“编辑:”后的蓝色文本,您将看到在文件上运行一小段代码后的样子。
  • @MadPhysicist 谢谢!你是 100% 正确的。根据您的建议,我已将其添加到我的代码中。现在应该很好用。
  • 也许 (a) 更新图片,并且 (b) 验证您没有替换任何链接目标
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 2017-05-12
相关资源
最近更新 更多