使用 python + 请求从链接下载多个 zip 文件

Using python + requests to download multiple zip files from links

我正在尝试从美国人口普查局下载压缩文件 (https://www2.census.gov/geo/tiger/TIGER2019/PLACE/). The code I have so far appeared to work, but all of the files downloaded are empty. Can someone help fill in what i'm missing?

from bs4 import BeautifulSoup as bs
import requests
import re

DOMAIN = "https://www2.census.gov/"
URL = "https://www2.census.gov/geo/tiger/TIGER2019/PLACE/"


def get_soup(URL):
    return bs(requests.get(URL).text, 'html.parser')

for link in get_soup(URL).findAll("a", attrs={'href': re.compile(".zip")}):
    file_link = link.get('href')
    print(file_link)

with open(link.text, 'wb') as file:
    response = requests.get(DOMAIN + file_link)
    file.write(response.content)

您似乎使用了错误的 links。

查看网站后,我可以看到下载 link 具有以下内容 URL:“https://www2.census.gov/geo/tiger/TIGER2019/PLACE/[file_link]",

所以目前您的 DOMAIN 变量是错误的,应该使用您的 URL 变量。

目前,"with open" 也不能与 for 循环中的所有 link 一起工作,因此只有最后一个 link 在当前状态下下载您的代码.