我一直在尝试为我公司的网络抓取项目获取所有美国邮政编码。 我正在尝试使用 uszipcode 库自动执行此操作,而不是从我感兴趣但无法弄清楚的网站手动执行。
这是我的手动尝试:
from bs4 import BeautifulSoup
import requests
url = 'https://www.unitedstateszipcodes.org'
headers = {'User-Agent': 'Chrome/50.0.2661.102'}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.text, 'html.parser')
hrefs = []
all_zipcodes = []
# Extract all
for data in soup.find_all('div', class_='state-list'):
for a in data.find_all('a'):
if a is not None:
hrefs.append(a.get('href'))
hrefs.remove(None)
def get_zipcode_list():
"""
get_zipcode_list gets the GET response from the web archives server using CDX API
:return: CDX API output in json format.
"""
for state in hrefs:
state_url = url + state
state_page = requests.get(state_url, headers=headers)
states_soup = BeautifulSoup(state_page.text, 'html.parser')
div = states_soup.find(class_='list-group')
for a in div.findAll('a'):
if str(a.string).isdigit():
all_zipcodes.append(a.string)
return all_zipcodes
这需要很多时间,并且想知道如何使用我们的邮政编码以更有效的方式做同样的事情
您可以尝试按模式搜索
s = SearchEngine()
l = s.by_pattern('', returns=1000000)
print(len(l))
docs 和他们的basic tutorial
中的更多细节engine = SearchEngine()
allzips = {}
for i in range(100000): #Get zipcode info for every possible 5-digit combination
zipcode = str(i).zfill(5)
try: allzips[zipcode] = engine.by_zipcode(zipcode).to_dict()
except: pass
#Convert dictionary to DataFrame
allzips = pd.DataFrame(allzips).T.reset_index(drop = True)
由于邮政编码只有 5 位数字,您最多可以迭代 100k,看看哪些邮政编码不会返回错误。该解决方案为您提供了一个 DataFrame,其中包含每个已保存邮政编码的所有存储信息
美国邮政编码的正则表达式是
[0-9]{5}(?:-[0-9]{4})?
你可以简单地检查 re 模块
import re
regex = r"[0-9]{5}(?:-[0-9]{4})?"
if re.match(zipcode, regex):
print("match")
else:
print("not a match")
我能够获得类似项目的 ~42,150 个邮政编码。想展示我的作品,因为我使用这个线程作为起点。
import us
from uszipcode import SearchEngine, SimpleZipcode
import os
#Creates a txt file named "zips" with zipcodes
#sorted by state then density
states = [state.name for state in us.states.STATES]
states.append('Washington DC')
engine = SearchEngine()
convertedList = ""
with open("zips.txt", "w") as f:
for i in states:
zipcodes = engine.query(state=i, sort_by=SimpleZipcode.population_density, zipcode_type=None, returns=50000)
print(i, len(zipcodes))
for i in zipcodes:
convertedList += i.zipcode + ", "
print("Total Zipcodes = ", "{:,}".format(len(convertedList)//7))
f.write(convertedList)
f.close()
#Remove trailing comma
with open("zips.txt", 'rb+') as f:
f.seek(-2, os.SEEK_END)
f.truncate()
f.close()
你可以这样得到所有的邮政编码:
from uszipcode import SearchEngine
sr = SearchEngine()
zipcodes = sr.by_coordinates(42, -71, radius=300000000, returns=0, zipcode_type=None)
默认情况下,查询函数只返回标准邮政编码。如果你想要所有邮政编码类型,你应该设置
zipcode_type=None
。设置 returns=0
删除返回结果数量的限制。
结果,你得到一个包含 42724 个元素的列表。
您可以从 官方来源) 下载邮政编码列表,然后解析它,如果它是一次性使用的,并且您不需要与每个邮政编码关联的任何其他元数据,例如 uszipcodes提供。
美国邮政编码还有另一个数据库,它非常大,应该有你需要的所有数据。
from uszipcode import SearchEngine
zipSearch = SearchEngine(simple_zipcode=False)
allZipCodes = zipSearch.by_pattern('', returns=200000)
print(len(allZipCodes)