【问题标题】:Python Curl writefunction not working onsecond callPython Curl writefunction 在第二次调用时不起作用
【发布时间】:2013-04-29 14:50:38
【问题描述】:

我用 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 ...

【问题讨论】:

  • 您可以在循环中尝试c.setopt(c.WRITEFUNCTION, f.write) 以避免将数据附加到同一个对象。如果Curl() 是可重用的,这可能就足够了。
  • 不,这不起作用,我以前尝试过,我认为它只是传递一个引用。第一页的字符串长度是否可能太大(网页相当大,与我用 Curl 和 Python 检索的其他内容相比。)

标签: python curl pycurl stringio


【解决方案1】:

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

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()

注意:

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

【讨论】:

  • "storage.getvalue() 返回从创建时写入存储的所有内容。"这就是我想听到的,可能我在其他脚本中没有注意到它,当用浏览器打开时它可能会被忽略,当用文本编辑器打开时它可能是可见的或类似的东西。
猜你喜欢
  • 1970-01-01
  • 2018-06-15
  • 2016-03-30
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多