Pythonでrequests.getで文字化けが起こってしまいます。
Python
1import requests 2 3r = requests.get("https://www.homepage-maker.jp/") 4print(r.encoding)
このモジュールを実行すると、
Python
1b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="jp" lang="jp">\n\n<head>\n<!-- Global site tag (gtag.js) - Google Analytics -->\n<script async src="https://www.googletagmanager.com/gtag/js?id=UA-4903005-4"></script>\n<script>\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag(\'js\', new Date());\n\n gtag(\'config\', \'UA-4903005-4\');\n</script>\n\n<meta http-equiv="content-type" content="text/html;charset=UTF-8" />\n<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">\n<title>\xe5\x88\x9d\xe5\xbf\x83\xe8\x80\x85\xe3\x81\xae\xe3\x81\x9f\xe3\x82\x81\xe3\x81\xae\xe3\x83\x9b\xe3\x83\xbc\xe3\x83\xa0\xe3\x83\x9a\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xae\xe4\xbd\x9c\xe3\x82\x8a\xe6\x96\xb9 [\xe6\xb1\xba\xe5\xae\x9a\xe7\x89\x88]</title>\n<meta name="description" content="\xe3\x83\x9b\xe3\x83\xbc\xe3\x83\xa0\xe3\x83\x9a\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xae\xe5\x88\x9d\xe5\xbf\x83\xe8\x80\x85\xe3\x81\xab\xe5\xbf\x85\xe8\xa6\x81\xe3\x81\xaa\xe6\x83\x85\xe5\xa0\xb1\xe3\x82\x92\xef\xbc\x95\xe3\x83\x9a\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xbe\xe3\x81\xa8\xe3\x82\x81\xe3\x81\xbe\xe3\x81\x97\xe3\x81\x9f\xe3\x80\x82\xe3\x81\x9f\xe3\x81\xa3\xe3\x81\x9f10\xe5\x88\x86\xe3\x80\x81\xe7\x9b\xae\xe3\x82\x92\xe9\x80\x9a\xe3\x81\x99\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xa7\xe3\x80\x8c\xe3\x83\x9b\xe3\x83\xbc\xe3\x83\xa0\xe3\x83\x9a\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xae\xe4\xbd\x9c\xe3\x82\x8a\xe6\x96\xb9\xe3\x80\x8d\xe3\x82\x92\xe7\x90\x86\xe8\xa7\xa3\xe3\x81\xa7\xe3\x81\x8d\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82" />\n<meta name="keywords" content="\xe3\x83\x9b\xe3\x83\xbc\xe3\x83\xa0\xe3\x83\x9a\xe3\x83\xbc\xe3\x82\xb8,\xe4\xbd...
本来なら普通に読める日本語が文字化けしてしまいます。
ですので、コードの中に
Python
1response.encoding = response.apparent_encoding
を挿入して、
Python
1import requests 2 3r = requests.get("https://www.homepage-maker.jp/") 4response.encoding = response.apparent_encoding 5print(r.content) 6
として実行するとエラーが出てしまいます。
Python
1Traceback (most recent call last): 2 File "test1.py", line 4, in <module> 3 response.encoding = response.apparent_encoding 4NameError: name 'response' is not defined
他の方法も試してみたのですが、全く文字化けが解消されません。
文字化けをどうすれば治せるか分かる方いらっしゃいますか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/07/06 13:50