从 python 2 到 python 3 的 Urllib 错误[重复]

问题描述 投票:0回答:1

我使用Python3.4,我想使用这个脚本。然而,它是为早期版本的 Python 制作的,因此不起作用。我希望有人能帮我把它改成 python 3 代码。我尝试将 urllib.request 导入为 urllib2 (因为显然 urllib2 已合并为 python 3)

import re
import sys
import urllib.request as urllib2
from bs4 import BeautifulSoup

usage = "Run the script: ./geolocate.py IPAddress"

if len(sys.argv)!=2:
    print(usage)
    sys.exit(0)

if len(sys.argv) > 1:
    ipaddr = sys.argv[1]

geody = "http://www.geody.com/geoip.php?ip=" + ipaddr
html_page = urllib2.urlopen(geody).read()
soup = BeautifulSoup.BeautifulSoup(html_page)

# Filter paragraph containing geolocation info.
paragraph = soup('p')[3]

# Remove html tags using regex.
geo_txt = re.sub(r'<.*?>', '', str(paragraph))
print geo_txt[32:].strip()
python urllib2 urllib
1个回答
1
投票
print geo_txt[32:].strip()

是Python 2。对于Python 3使用

print(geo_txt[32:].strip())
© www.soinside.com 2019 - 2024. All rights reserved.