下载链接中的空白python beautifulsoup



我正试图从这个网站下载地理数据:

http://www.catastro.minhap.es/INSPIRE/CadastralParcels/08/ES.SDGC.CP.atom_08.xml

它拥有来自多个城市的数据集。

以下是我正在运行的代码,用于获取与.zip文件的链接:

import requests
import urllib
import time
from bs4 import BeautifulSoup
url = 'http://www.catastro.minhap.es/INSPIRE/CadastralParcels/08/ES.SDGC.CP.atom_08.xml'
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

然后我通过获得数据集列表

for link in soup.find_all('link'):
print(link.get('href'))

问题来了,那些属于名字有多个单词的市政当局的链接,意思是上面有空格,比如:

code_mun = '08002'

nom_mun = 'AGUILAR DE SEGARRA'

我无法使用以下脚本检索数据:

download_url = 'http://www.catastro.minhap.es/INSPIRE/CadastralParcels/08/' + code_mun + '-' + nom_mun + '/A.ES.SDGC.CP.'+ code_mun + ".zip"`
out = my_path
urllib.request.urlretrieve(download_url, my_path + '.zip')

关键是,如果您复制/粘贴链接并将其运行到它工作的web浏览器中,它会下载文件,但如果您运行脚本,则不会下载。

我试过使用nom_mun.replace(' ', '%'),但效果不太好。

有什么帮助吗?

urllib完成了这项工作,但您不需要它:

import urllib.parse
code_mun = '08002'
nom_mun = urllib.parse.quote('AGUILAR DE SEGARRA')
download_url = f"http://www.catastro.minhap.es/INSPIRE/CadastralParcels/08/{code_mun}-{nom_mun}/A.ES.SDGC.CP.{nom_mun}.zip"

下载以下代码:

import requests
from bs4 import BeautifulSoup
url = 'http://www.catastro.minhap.es/INSPIRE/CadastralParcels/08/ES.SDGC.CP.atom_08.xml'
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
links = soup.select("entry link")
for link in links:
href = link["href"]
file_name = href.split('/')[-1]
with open(file_name, 'wb') as f:
f.write(requests.get(link["href"]).content)

最新更新