Python无权访问此服务器 / 从邮政编码返回城市/州

6

我想要做的是从邮编中获取城市和州。以下是我的进展:

def find_city(zip_code):
    zip_code = str(zip_code)
    url = 'http://www.unitedstateszipcodes.org/' + zip_code
    source_code = requests.get(url)
    plain_text = source_code.text
    index = plain_text.find(">")
    soup = BeautifulSoup(plain_text, "lxml")
    stuff = soup.findAll('div', {'class': 'col-xs-12 col-sm-6 col-md-12'})

我也尝试使用id="zip-links",但那没用。但是问题在于:当我运行print(plain_text)时,我得到了以下结果:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /80123
on this server.<br />
</p>
</body></html>

所以我的问题是:是否有更好的方法从邮政编码获取城市和州?或者是unitedstateszipcodes.gov不合作的原因。毕竟,很容易看到源代码、标签和文本。谢谢。


这并不是一个Python问题,但你可以尝试使用邮局的网站:https://tools.usps.com/go/ZipLookupResultsAction!input.action?resultMode=2&postalCode=10023 - Gadi
2个回答

15

您需要添加一个用户代理:

headers = {"User-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36"}
def find_city(zip_code):
    zip_code = str(zip_code)
    url = 'http://www.unitedstateszipcodes.org/' + zip_code
    source_code = requests.get(url,headers=headers)

一旦你这样做,响应代码就是 200,并且你会得到源代码:

In [8]:  url = 'http://www.unitedstateszipcodes.org/54115'

In [9]: headers = {"User-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36"}

In [10]:  url = 'http://www.unitedstateszipcodes.org/54115'
In [11]: source_code = requests.get(url,headers=headers)
In [12]: source_code.status_code
Out[12]: 200

如果你想要详细信息,那么它很容易解析:

In [59]:  soup = BeautifulSoup(plain_text, "lxml")

In [60]: soup.find('div', id='zip-links').h3.text
Out[60]: 'ZIP Code: 54115'

In [61]: soup.find('div', id='zip-links').h3.next_sibling.strip()
Out[61]: 'De Pere, WI 54115'

In [62]:  url = 'http://www.unitedstateszipcodes.org/90210'

In [63]: source_code = requests.get(url,headers=headers).text

In [64]:  soup = BeautifulSoup(source_code, "lxml")

In [65]: soup.find('div', id='zip-links').h3.text
Out[66]: 'ZIP Code: 90210'

In [70]: soup.find('div', id='zip-links').h3.next_sibling.strip()
Out[70]: 'Beverly Hills, CA 90210'

你也可以将每个结果存储在数据库中,并首先尝试在数据库中进行查找。


2
我认为你正在采取一种更长的路线来解决一个简单的问题!
尝试使用pyzipcode
>>> from pyzipcode import ZipCodeDatabase
>>> zcdb = ZipCodeDatabase()
>>> zipcode = zcdb[54115]
>>> zipcode.zip
u'54115'
>>> zipcode.city
u'De Pere'
>>> zipcode.state
u'WI'
>>> zipcode.longitude
-88.078959999999995
>>> zipcode.latitude
44.42042
>>> zipcode.timezone
-6

我实际上无法让pyzipcode工作(有时我的模块无法下载),但最终我使用了你发送的链接中的.csv文件。pyzipcode只适用于Linux吗,因为我只看到了一个.tar.gz链接? - MANA624
使用 pip 下载模块。 - python
Pip也失败了 :( 我又看到它在下载x.tar.gz,但我不确定为什么。 - MANA624

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接