使用 BeautifulSoup 从 url 下载并导出 zip 文件

Downloading and exporting a zip file from url using BeautifulSoup

我查看了对以前的 zip 下载问题的答复,并且 运行 一直在解决问题。我使用 BeatifulSoup 来识别我想使用以下代码下载的特定 zip 文件:

state_fips = '06'
county_fips = '037'
url = 'https://www2.census.gov/geo/tiger/TIGER2020/ROADS/'
url_get = requests.get(url)
soup = BeautifulSoup(url_get.content, 'html.parser')

# get state and county fips
st_cnty_string = f'tl_2020_{state_fips}{county_fips}'

然后我尝试读取数据并将数据写入文件,但我不断收到错误或文件有 0 个字节。我不确定 problem/s is/are:

在哪里
link = soup.findAll('a', attrs={'href': re.compile(st_cnty_string)})
data = urllib.request.urlretrieve(url, link.get('href'))
open('test.zip', 'wb').write(data)

这次尝试出现以下错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: a bytes-like object is required, not 'tuple'

如有任何帮助,我们将不胜感激!

一个问题是 BeautifulSoup returns 相关链接。但是您需要完整的 url 才能下载 zip 文件。

试试这个:

for link in soup.findAll('a', attrs={'href': re.compile(st_cnty_string)}):
    link_abs = f'{url}/{link.get("href")}'
    with open('test.zip', 'wb') as f:
        f.write(requests.get(link_abs).content)