0

我正在编写一个 Python 脚本,以在对网页进行更改时通知我,并将页面的当前状态存储到文件中,以便在重新启动后无缝恢复。代码如下:

import urllib
url="http://example.com"
filepath="/path/to/file.txt"
try:
    html=open(filepath,"r").read() # Restores imported code from previous session
except:
    html="" # Blanks variable on first run of the script
while True:
    imported=urllib.urlopen(url)
    if imported!=html:
    # Alert me
    html=imported
    open(filepath,"w").write(html)
# Time delay before next iteration

运行脚本返回:

Traceback (most recent call last):
  File "April_Fools.py", line 20, in <module>
    open(filepath,"w").write(html)
TypeError: expected a character buffer object

------------------
(program exited with code: 1)
Press return to continue

我不知道这意味着什么。我对 Python 比较陌生。任何帮助将非常感激。

4

2 回答 2

1

urllib.urlopen不返回字符串,而是将响应作为类似文件的对象返回。您需要阅读该回复:

html = imported.read()

只有这样html您才能将字符串写入文件。

于 2013-03-31T18:53:25.133 回答
1

顺便说一句, usingopen(filename).read()被认为是好的样式,因为您从不关闭文件。写作也是如此。尝试使用上下文管理器

try:
    with open(filepath,"r") as htmlfile:
        html = htmlfile.read()
except:
    html=""

当您离开该块时,该with块将自动关闭文件。

于 2013-03-31T19:19:23.030 回答