2

我是 Python 新手,在编写程序时遇到了一个问题,该程序会将我的背景更改为“今日国家地理图片”。它可以很好地获取 jpeg 的路径,但是当我使用命令更改桌面背景(对于 Windows)时,它只会将背景更改为纯黑色。代码本身不会引发任何错误,它只是无法按照我想要的方式工作。这是代码。

import urllib2
import ctypes

SPI_SETDESKWALLPAPER = 20
url = urllib2.urlopen("http://photography.nationalgeographic.com/photography/photo-of-the-day/")
code = url.readlines()
pos = code[1303].split("\"",2)
imgurl = pos[1]
print imgurl
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, imgurl , 0)
4

2 回答 2

2

您似乎将 URL 传递给 set wallpaper 命令,而不是图像的路径。首先获取图像。试试这样吧。

import urllib2
import ctypes

SPI_SETDESKWALLPAPER = 20
url = urllib2.urlopen("http://photography.nationalgeographic.com/photography/photo-of-the-day/")
code = url.readlines()
pos = code[1303].split("\"",2)
imgurl = pos[1]

print imgurl
# Changes after here
url2 = urllib2.urlopen(imgurl)
out = open("wallpaper.jpg", "wb")
out.write(url2.read())
out.close()
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "wallpaper.jpg" , 0)

我实际上没有尝试过(不在Windows上运行)所以也许它会解决问题,也许不会!

PS,这是用于解析 url 的非常脆弱的代码,但是让它工作的荣誉!

于 2012-05-05T20:09:01.683 回答
0

The code you use to parse the url is indeed very fragile. You would be better of using a regex. This regex searches for the unique div containing the image and then removes everything but the url.
Also, using with to open a file is better, because it automatically closes the file.
The improved code would then be:

import urllib2
import ctypes
import re

SPI_SETDESKWALLPAPER = 20
url = urllib2.urlopen("http://photography.nationalgeographic.com/photography/photo-of-the-day/")
code = url.read()
imgurl = re.sub(r'(.|\n)+?<div class="primary_photo">(.|\n)+?<img src="(.+?)"(.|\n)+', r'\3', code)

print imgurl
url2 = urllib2.urlopen(imgurl)
with open("wallpaper.jpg", "wb") as f:
    f.write(url2.read())
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "wallpaper.jpg" , 0)
于 2012-05-05T22:29:26.770 回答