如何使用美丽的汤保存网站的附件?



我写了一个代码来抓取网站中附加的附件。它实质上是抓取指向附件的超链接。我无法找到一种将直接保存这些附件保存在本地位置的方法。

import requests
import pandas as pd 
from requests import get
url = 'https://www.amfiindia.com/research-information/amfi-monthly'
response = get(url,verify=False)
import bs4
from bs4 import BeautifulSoup
html_soup = BeautifulSoup(response.content,'html.parser')
filetype = '.xls'
excel_sheets = html_soup.find_all('a')
#File name where the links to the excel sheet needs to be saved --> here: "All_Links_2.csv"
destination = open('All_Links_2.csv','wb')
for link in excel_sheets:
href = link.get('href') + 'n'
if filetype in href:
print(href)

谁能在这里帮忙??

这不是你用漂亮的汤做的事情,而是我们使用urllib库。

import urllib.request
urllib.request.urlretrieve(href, "file.jpg")

这将获取图像地址并将其另存为file.jpg。如果你想要不同的文件名,这适用于你的情况,使字符串"file" + i + ".jpg"i是你递增的一些值

如果您尝试仅获取链接,则不需要二进制模式,而且由于您导入了熊猫,因此您可以使用它来保存它们。

首先创建一个数据帧:

df = pd.DataFrame([a['href'] for a in excel_sheets if filetype in a['href']])

然后只需保存它而不带列名称(header=False(:

df.to_csv('All_Links_2.csv', header=False)

最新更新