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

时间:2020-06-30 16:57:56

标签: python web-scraping beautifulsoup python-requests re

我正在尝试从美国人口普查局(https://www2.census.gov/geo/tiger/TIGER2019/PLACE/)下载压缩文件。到目前为止,我的代码似乎正常工作,但是下载的所有文件都是空的。有人可以帮我填写我所缺少的吗? enter image description here

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)

1 个答案:

答案 0 :(得分:0)

您似乎使用了错误的链接。

浏览网站后,我可以看到下载链接具有以下URL:“ https://www2.census.gov/geo/tiger/TIGER2019/PLACE/[fi​​le_link]”,

因此,当前您的DOMAIN变量是错误的,应该使用URL变量。

当前,“ with open”也未缩进以与for循环中的所有链接一起使用,因此,在当前状态下,仅下载了您的代码中的最后一个链接。