使用 uszipcode 的所有美国邮政编码列表

List of all US ZIP Codes using uszipcode

我一直在尝试为我公司的网络抓取项目获取所有美国邮政编码。 我正在尝试使用 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

这需要很多时间,并且想知道如何使用 uszipcodes 以更有效的方式做同样的事情

您可以尝试按模式“”搜索

s = SearchEngine()
l = s.by_pattern('', returns=1000000)
print(len(l))

docs and in their basic tutorial

中有更多详细信息

美国邮政编码的正则表达式是[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")

您可以从 official source(42k+ rows) and then parse it if its for one-time use and you don't need any other metadata associated with each of the zip codes like the one which uszipcodes 提供的 csv 格式下载邮政编码列表。

uszipcodes 也有 another database,它相当大,应该有你需要的所有数据。

from uszipcode import SearchEngine
zipSearch = SearchEngine(simple_zipcode=False)
allZipCodes = zipSearch.by_pattern('', returns=200000)
print(len(allZipCodes)