简体   繁体   English

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

[英]Downloading and exporting a zip file from url using BeautifulSoup

I have looked over the responses to previous zip downloading questions and I keep running into problems.我查看了对之前 zip 下载问题的回复,但我一直遇到问题。 I used BeatifulSoup to identify a particular zip file I want to download using the following code:我使用 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}'

I then try to read and write the data to a file but I keep getting errors or files that have 0 bytes.然后我尝试读取数据并将其写入文件,但我不断收到错误或具有 0 字节的文件。 I am not sure where the 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)

I get the following error for this attempt:我收到此尝试的以下错误:

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

Any help would be much appreciated!任何帮助将非常感激!

One problem is that BeautifulSoup returns relative links.一个问题是 BeautifulSoup 返回相对链接。 But you need a complete url to download the zipfile.但是你需要一个完整的 url 来下载压缩文件。

Try this:尝试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM