【问题标题】:List of all US ZIP Codes using uszipcode使用 uszipcode 的所有美国邮政编码列表
【发布时间】:2021-12-30 11:12:06
【问题描述】:

我一直在尝试为我公司的网络抓取项目获取所有美国邮政编码。 我正在尝试使用 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 以更有效的方式做同样的事情

【问题讨论】:

  • 您需要什么格式的数据?
  • 所有美国邮政编码的列表
  • 那么下面@luca 的回答应该会给你。

标签: python web-scraping zipcode


【解决方案1】:

您可以尝试按模式''搜索

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

docs 和他们的basic tutorial 中的更多详细信息

【讨论】:

  • 这产生 29973,应该在 40k 左右
【解决方案2】:

您可以从official source(42k+ 行)以 csv 格式下载邮政编码列表,然后解析它以供一次性使用,并且您不需要与每个邮政编码关联的任何其他元数据就像uszipcodes 提供的一样。

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多