Python 如何将url的内容保存到.txt文件?
代码失败了 有人能帮忙吗 我在堆栈溢出中搜索,并尝试了一些方法,但似乎找不到任何有效的方法Python 如何将url的内容保存到.txt文件?,python,html,url,Python,Html,Url,代码失败了 有人能帮忙吗 我在堆栈溢出中搜索,并尝试了一些方法,但似乎找不到任何有效的方法 from urllib.request import urlopen link = "https://www.youtube.com/live_chat?v=IKQkjWmqQv8&is_popout=1" f = urlopen(link) myfile = f.read() print (myfile) output_file = open('1.txt','w') output_file
from urllib.request import urlopen
link = "https://www.youtube.com/live_chat?v=IKQkjWmqQv8&is_popout=1"
f = urlopen(link)
myfile = f.read()
print (myfile)
output_file = open('1.txt','w')
output_file.write(myfile)
output_file.close()
您将从
read()
中获得一个字节,您可以通过添加b
以二进制模式将其写入文件,如下所示:
from urllib.request import urlopen
link = "https://www.youtube.com/live_chat?v=IKQkjWmqQv8&is_popout=1"
f = urlopen(link)
myfile = f.read()
print (myfile)
with open('output.html','wb') as output_file:
output_file.write(myfile)
注意:使用
和
是处理文件的首选方法。之后它会自动为您关闭文件。如果您从读取()中得到一个字节,您可以通过添加b
以二进制模式将其写入文件,如下所示:
from urllib.request import urlopen
link = "https://www.youtube.com/live_chat?v=IKQkjWmqQv8&is_popout=1"
f = urlopen(link)
myfile = f.read()
print (myfile)
with open('output.html','wb') as output_file:
output_file.write(myfile)
注意:使用和
是处理文件的首选方法。之后它会自动为您关闭文件。请尝试以下代码:
from urllib.request import urlopen
link = "https://www.youtube.com/live_chat?v=IKQkjWmqQv8&is_popout=1"
f = urlopen(link)
myfile = f.read()
print (myfile)
output_file = open('1.txt','wb')
output_file.write(myfile)
output_file.close()
请尝试以下代码:
from urllib.request import urlopen
link = "https://www.youtube.com/live_chat?v=IKQkjWmqQv8&is_popout=1"
f = urlopen(link)
myfile = f.read()
print (myfile)
output_file = open('1.txt','wb')
output_file.write(myfile)
output_file.close()
其他答案是正确的,但您可以将字节解码为字符串。为此,只需修改以下两行:
...
output_file = open('1.txt', 'w', encoding="utf8")
output_file.write(myfile.decode("utf8"))
...
其他答案是正确的,但您可以将字节解码为字符串。为此,只需修改以下两行:
...
output_file = open('1.txt', 'w', encoding="utf8")
output_file.write(myfile.decode("utf8"))
...
请为您的文件模式尝试'wb'
。可能是重复的,谢谢。它起作用了。但是,无法加载网站的内容。它说浏览器版本不支持您的文件模式使用try'wb'
。可能是重复的,谢谢。它起作用了。但是,无法加载网站的内容。它说浏览器版本不支持。谢谢。它起作用了。但是,无法加载网站的内容。它说浏览器版本不支持。我建议您将输出文件重命名为output.html
,然后尝试将其加载到您的浏览器中。谢谢。它起作用了。但是,无法加载网站的内容。它说浏览器版本不支持。我建议您将输出文件重命名为output.html
,然后尝试将其加载到您的浏览器中。谢谢。它起作用了。但是,无法加载网站的内容。它说浏览器版本不支持。谢谢。它起作用了。但是,无法加载网站的内容。它说浏览器版本不支持。谢谢。它起作用了。但是,无法加载网站的内容。它说浏览器版本不支持。谢谢。它起作用了。但是,无法加载网站的内容。它说浏览器版本不支持