我一直在嘗試為我公司的網路抓取專案獲取所有美國郵政編碼。我正在嘗試使用 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 以更有效的方式執行相同的操作
uj5u.com熱心網友回復:
您可以嘗試按模式 '' 搜索
s = SearchEngine()
l = s.by_pattern('', returns=1000000)
print(len(l))
檔案及其基本教程中的更多詳細資訊
uj5u.com熱心網友回復:
您可以從官方來源(42k 行)下載郵政編碼串列作為 csv ,然后決議它,如果它是一次性使用的,并且您不需要任何其他與每個郵政編碼相關的元資料,例如uszipcodes提供。
uszipcodes 還有另一個資料庫,它非常大,應該有你需要的所有資料。
from uszipcode import SearchEngine
zipSearch = SearchEngine(simple_zipcode=False)
allZipCodes = zipSearch.by_pattern('', returns=200000)
print(len(allZipCodes)
uj5u.com熱心網友回復:
美國郵政編碼的正則運算式是 [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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401185.html
