Python Curl writefunction在第二次调用时不起作用

Python Curl writefunction在第二次调用时不起作用,python,curl,pycurl,stringio,Python,Curl,Pycurl,Stringio,我已经用Python编写了一个简单的脚本 它解析网页中的超链接,然后检索这些链接以解析某些信息 我有类似的脚本运行并重新使用writefunction,没有任何问题,因为某种原因它失败了,我不知道为什么 通用旋度初始化: storage = StringIO.StringIO() c = pycurl.Curl() c.setopt(pycurl.USERAGENT, USER_AGENT) c.setopt(pycurl.COOKIEFILE, "") c.setopt(pycurl.POST

我已经用Python编写了一个简单的脚本

它解析网页中的超链接,然后检索这些链接以解析某些信息

我有类似的脚本运行并重新使用writefunction,没有任何问题,因为某种原因它失败了,我不知道为什么

通用旋度初始化:

storage = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(pycurl.USERAGENT, USER_AGENT)
c.setopt(pycurl.COOKIEFILE, "")
c.setopt(pycurl.POST, 0)
c.setopt(pycurl.FOLLOWLOCATION, 1)
#Similar scripts are working this way, why this script not?
c.setopt(c.WRITEFUNCTION, storage.write)
第一次调用检索链接:

URL = "http://whatever"
REFERER = URL

c.setopt(pycurl.URL, URL)
c.setopt(pycurl.REFERER, REFERER)
c.perform()

#Write page to file
content = storage.getvalue()
f = open("updates.html", "w")
f.writelines(content)
f.close()
... Here the magic happens and links are extracted ...
现在循环这些链接:

for i, member in enumerate(urls):
    URL = urls[i]
    print "url:", URL
    c.setopt(pycurl.URL, URL)
    c.perform()

    #Write page to file
    #Still the data from previous!
    content = storage.getvalue()
    f = open("update.html", "w")
    f.writelines(content)
    f.close()
    #print content
    ... Gather some information ...
    ... Close objects etc ...

如果要按顺序将URL下载到不同的文件(无并发连接):

注:

  • storage.getvalue()
    返回从创建
    storage
    开始写入的所有内容。在您的情况下,您应该在其中找到来自多个URL的输出
  • open(filename,“w”)
    覆盖文件(以前的内容已消失),即
    update.html
    包含循环最后一次迭代时
    内容中的内容

您可以在循环中尝试
c.setopt(c.WRITEFUNCTION,f.write)
,以避免向同一对象追加数据。如果
Curl()
是可重用的,那就足够了。不,那不行,我以前试过,我想这只是传递一个引用。是否第一页的字符串长度太大(与我使用Curl和Python检索的其他内容相比,网页相当大。)“storage.getvalue()返回从创建存储时就写入存储的所有内容。”这是我想听到的,可能我在其他脚本中没有注意到,当使用浏览器打开时,它可能会被忽略;当使用文本编辑器打开时,它可能会可见或类似于此。
for i, url in enumerate(urls):
    c.setopt(pycurl.URL, url)
    with open("output%d.html" % i, "w") as f:
        c.setopt(c.WRITEDATA, f) # c.setopt(c.WRITEFUNCTION, f.write) also works
        c.perform()