如何下载和修改完整的网页?

2024-05-21 05:14:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想下载世界上最有趣的笑话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而没有格式

我能做什么?我不介意一些手动步骤(比如,先把文件下载到某个地方)

谢谢


Tags: 文件httpsorgapplehtmlwiki世界页面
1条回答
网友
1楼 · 发布于 2024-05-21 05:14:39

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

#! 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)

编辑: 加上疯狂物理学家的建议,将取代所有的笑话

Proof of work, with edits fully working and comprehensively replacing all string variants of the word "joke"

谢谢

相关问题 更多 >