0

Python で簡単なスクリプトを作成しました。

Web ページからハイパーリンクを解析し、その後、これらのリンクを取得して情報を解析します。

同様のスクリプトを問題なく実行して書き込み関数を再利用していますが、何らかの理由で失敗し、その理由がわかりません。

一般的なカールの初期化:

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 ...
4

1 に答える 1

0

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
于 2013-05-06T19:18:35.030 に答える