【发布时间】: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