Мой код неправильно загружает файл CSV с URL-адреса с помощью Python - PullRequest
0 голосов
/ 10 мая 2019

Я создал некоторый код для загрузки файла CSV с URL-адреса. Код загружает HTML-код ссылки, но когда я копирую созданный в браузере URL-адрес, он работает, а в коде - нет.

Я пробовал os, response и urllib, но все эти опции давали одинаковый результат.

Это ссылка, которую я в конечном итоге хочу скачать как CSV: https://www.ishares.com/uk/individual/en/products/251567/ishares-asia-pacific-dividend-ucits-etf/1506575576011.ajax?fileType=csv&fileName=IAPD_holdings&dataType=fund

import requests
#this is the url where the csv is
url='https://www.ishares.com/uk/individual/en/products/251567/ishares-asia-pacific-dividend-ucits-etf?switchLocale=y&siteEntryPassthrough=true'
r = requests.get(url, allow_redirects=True)
response = requests.get(url)
if response.status_code == 200:
    print("Success")
else:
    print("Failure")

#find the url for the CSV
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.content,'lxml')
for i in soup.find_all('a',{'class':"icon-xls-export"}):
    print(i.get('href'))

# I get two types of files, one CSV and the other xls. 
link_list=[]
for i in soup.find_all('a', {'class':"icon-xls-export"}):
    link_list.append(i.get('href'))

# I create the link with the CSV
url_csv = "https://www.ishares.com//"+link_list[0]
response_csv = requests.get(url_csv)
if response_csv.status_code == 200:
    print("Success")
else:
    print("Failure")

#Here I want to download the file
import urllib.request
with urllib.request.urlopen(url_csv) as holdings1, open('dataset.csv', 'w') as f:
    f.write(holdings1.read().decode())

Я хочу загрузить данные CSV.

1 Ответ

0 голосов
/ 10 мая 2019

Для корректной работы требуются файлы cookie

Я использую requests.Session() для автоматического получения и хранения файлов cookie.

И я пишу в файл response_csv.content, потому что он у меня уже есть после повторных запросов - поэтому мне не нужно делать другие запросы.И потому что с помощью urllib.request я буду создавать запросы без файлов cookie, и это может не работать.

import requests
from bs4 import BeautifulSoup

s = requests.Session()

url='https://www.ishares.com/uk/individual/en/products/251567/ishares-asia-pacific-dividend-ucits-etf?switchLocale=y&siteEntryPassthrough=true'

response = s.get(url, allow_redirects=True)

if response.status_code == 200:
    print("Success")
else:
    print("Failure")

#find the url for the CSV
soup = BeautifulSoup(response.content,'lxml')

for i in soup.find_all('a',{'class':"icon-xls-export"}):
    print(i.get('href'))

# I get two types of files, one CSV and the other xls. 
link_list=[]
for i in soup.find_all('a', {'class':"icon-xls-export"}):
    link_list.append(i.get('href'))

# I create the link with the CSV
url_csv = "https://www.ishares.com//"+link_list[0]

response_csv = s.get(url_csv)

if response_csv.status_code == 200:
    print("Success")
    f = open('dataset.csv', 'wb')
    f.write(response_csv.content)
    f.close()
else:
    print("Failure")
...