mechanize.Browser() 在 Windows 下下载损坏的 JPG,在 Linux 下工作正常吗?

发布于 2024-12-11 22:48:29 字数 566 浏览 0 评论 0原文

我有以下代码:

self.bg_br = mechanize.Browser()   

self.bg_br.retrieve(self.bg_imageurl, "image2.jpg")

self.bg_file2 = open("image.jpg", mode="w")
self.bg_image = self.bg_br.open(self.bg_imageurl).read()
self.bg_file2.write(self.bg_image)
self.bg_file2.close()

问题是 image.jpg (通过 .read() 方法下载的 image.jpg 已损坏。稍后由 Qt 显示(报告“JPG 损坏”错误) ),当我尝试使用 Windows 应用程序打开该文件时,图像打开正常,但

通过 .retrieve 方法,一切正常,但是,图像我。正在下载每次访问链接时都会重新生成 - 所以这不好,

两种方法在 Linux 下都可以正常工作,但是在 Windows 下,就像我说的,第一种方法给出了损坏的图像。

I have the following code:

self.bg_br = mechanize.Browser()   

self.bg_br.retrieve(self.bg_imageurl, "image2.jpg")

self.bg_file2 = open("image.jpg", mode="w")
self.bg_image = self.bg_br.open(self.bg_imageurl).read()
self.bg_file2.write(self.bg_image)
self.bg_file2.close()

The problem is that the image.jpg (the one that is downloaded via .read() method is corrupted. This is displayed later by Qt (which reports "JPG corrupted" error), and when I try to open the file with a windows application, the image is garbled. It opens fine, but it's garbled.

Via the .retrieve method, everything works fine, HOWEVER, the image I am downloading is generated anew every time you visit the link - so that's no good.

What's even more puzzling is that both methods work just fine under linux, however under windows, like I said, the first method gives a corrupt image.

Help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪落纷纷 2024-12-18 22:48:29

您需要使用 'wb' 模式打开文件来执行 bg_file2 操作。在 Unix 下,Python 不区分文本文件和二进制文件,但在 Windows 上它会区分。为了支持平台独立性,只需使用'wb'模式以二进制格式写入图像。我不知道 mechanize 的内部原理,但我的猜测是 retrieve 方法也执行此操作:您只是看不到它,因为它是由库抽象的。

有关更多详细信息,请参阅Python 文档的此部分

You need to open the file using the 'wb' mode for your bg_file2 operation. Under Unix, Python doesn't differentiate between text and binary files, but on Windows it does. To support platform independence, just use the 'wb' mode to write your image in a binary format. I don't know the internals of mechanize, but my guess is that the retrieve method does this as well: you just don't see it as it is abstracted by the library.

For more details, see this section of the Python docs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文