python-2.7 - 从 URL 下载所有 csv 文件

标签 python-2.7 csv download beautifulsoup

我想下载所有 csv 文件,知道我该怎么做吗?

from bs4 import BeautifulSoup
import requests
url = requests.get('http://www.football-data.co.uk/englandm.php').text
soup = BeautifulSoup(url)
for link in soup.findAll("a"):
    print link.get("href")

最佳答案

像这样的东西应该可以工作:

from bs4 import BeautifulSoup
from time import sleep
import requests


if __name__ == '__main__':
    url = requests.get('http://www.football-data.co.uk/englandm.php').text
    soup = BeautifulSoup(url)
    for link in soup.findAll("a"):
        current_link = link.get("href")
        if current_link.endswith('csv'):
            print('Found CSV: ' + current_link)
            print('Downloading %s' % current_link)
            sleep(10)
            response = requests.get('http://www.football-data.co.uk/%s' % current_link, stream=True)
            fn = current_link.split('/')[0] + '_' + current_link.split('/')[1] + '_' + current_link.split('/')[2]
            with open(fn, "wb") as handle:
                for data in response.iter_content():
                    handle.write(data)

关于python-2.7 - 从 URL 下载所有 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39033674/

相关文章:

image - 如何在单个 XML 调用中下载多个图像?

python - 从 os.walk 中有效地删除 dirnames 中的子目录

python - 无法使用 sqlalchemy 查询 json 列

python - 如何使用 defaultdict 创建带有 lambda 函数的字典?

python - 在 Python 中截断文件头

python - 使用 python csv writer 在文本字段中换行

sql - 将 CSV 文件导入 MySQL 数据库的工具?

google-analytics - GA的下载代码无效

javascript - 在 JavaScript 中创建并保存到文件新的 png 图像

perl - 在 Perl 中解析带双引号的制表符分隔文件