0

Windows 7 で python 3.3.0 を使用しています。

システム上でバイパスするようにこのスクリプトを作成しhttp proxy without authenticationました。しかし、実行するとエラーが発生UnicodeEncodeError: 'charmap' codec can't encode characters in position 6242-6243: character maps to <undefined> します。Unicode 文字を文字列にデコードできないようです。

では、何を使用または編集/実行する必要がありますか? 誰にも手がかりや解決策はありますか?

.pyには以下が含まれます:

import sys, urllib
import urllib.request

url = "http://www.python.org"
proxies = {'http': 'http://199.91.174.6:3128/'}

opener = urllib.request.FancyURLopener(proxies)

try:
    f = urllib.request.urlopen(url)
except urllib.error.HTTPError as  e:
    print ("[!] The connection could not be established.")
    print ("[!] Error code: ",  e.code)
    sys.exit(1)
except urllib.error.URLError as  e:
    print ("[!] The connection could not be established.")
    print ("[!] Reason: ",  e.reason)
    sys.exit(1)

source = f.read()

if "iso-8859-1" in str(source):
    source = source.decode('iso-8859-1')
else:
    source = source.decode('utf-8')

print("\n SOURCE:\n",source)
4

1 に答える 1

2
  1. このコードはプロキシを使用していません
  2. この形式のエンコード検出は非常に脆弱です。明確に定義された場所で宣言されたエンコーディングのみを探す必要があります: HTTP ヘッダーの「Content-Type」と、応答が charset メタタグの HTML である場合。
  3. スタックトレースを含めなかったので、行でエラーが発生したと思います if "iso-8859-1" in str(source):。への呼び出しstr()は、システムのデフォルト エンコーディング ( ) を使用してバイト データをデコードしますsys.getdefaultencoding()。本当にこのチェックを維持したい場合 (ポイント 2 を参照) を実行する必要があります。 if b"iso-8859-1" in source:これは文字列ではなくバイトに対して機能するため、事前にデコードを行う必要はありません。

注: このコードは私にとっては問題なく動作します。おそらく、私のシステムはデフォルトの utf-8 エンコーディングを使用しているのに対し、あなたの Windows システムは別のものを使用しているためです。

更新: Pythonで http を実行する場合は、python-requestsを使用することをお勧めします。

import requests

proxies = {'http': your_proxy_here}

with requests.Session(proxies=proxies) as sess:
    r = sess.get('http://httpbin.org/ip')
    print(r.apparent_encoding)
    print(r.text)
    # more requests

注: これは HTML で指定されたエンコーディングを使用しません。それを抽出するには、beautifulsoup のような HTML パーサーが必要です。

于 2013-03-03T18:50:15.567 に答える