2

txt既存の URL をパラメーターとして渡して、HTML を単一のファイルにロードしようとしています。

for line in open('C:\Users\me\Desktop\URLS-HERE.txt'):
 if line.startswith('http') and line.endswith('html\n') :
    fichier = open("C:\Users\me\Desktop\other.txt", "a")
    allhtml = urllib.urlopen(line)
    fichier.write(allhtml)
    fichier.close()

しかし、私は次のエラーが発生します:

TypeError: expected a character buffer object
4

2 に答える 2

3

によって返される値はurllib.urlopen()オブジェクトのようなファイルです。一度開いたらread()、次のスニペットに示すように、メソッドを使用して読み取る必要があります。

for line in open('C:\Users\me\Desktop\URLS-HERE.txt'):
   if line.startswith('http') and line.endswith('html\n') :
      fichier = open("C:\Users\me\Desktop\other.txt", "a")
      allhtml = urllib.urlopen(line)
      fichier.write(allhtml.read())
      fichier.close()

お役に立てれば!

于 2012-08-18T09:17:57.767 に答える
1

ここでの問題は、urlopenHTML を取得するファイル オブジェクトへの参照を返すことです。

for line in open(r"C:\Users\me\Desktop\URLS-HERE.txt"):
 if line.startswith('http') and line.endswith('html\n') :
    fichier = open(r"C:\Users\me\Desktop\other.txt", "a")
    allhtml = urllib2.urlopen(line)
    fichier.write(allhtml.read())
    fichier.close()

urllib.urlopenPython 2.6以降、関数は非推奨としてマークされていることに注意してください。代わりに使用することをお勧めしますurllib2.urlopen

さらに、コード内のパスの操作には注意が必要です。それぞれエスケープする必要があります\

"C:\\Users\\me\\Desktop\\other.txt"

またはr、文字列の前にプレフィックスを使用します。'r' または 'R' プレフィックスが存在する場合、バックスラッシュに続く文字は変更されずに文字列に含まれます。

r"C:\Users\me\Desktop\other.txt"
于 2012-08-18T09:29:10.533 に答える