【发布时间】:2021-08-27 09:02:09
【问题描述】:
所以我需要在CoinGecko上下载列表中每一个硬币的图片,所以我写了如下代码:
import requests
from bs4 import BeautifulSoup
from os.path import basename
def getdata(url):
r = requests.get(url)
return r.text
htmldata = getdata("https://www.coingecko.com/en")
soup = BeautifulSoup(htmldata, 'html.parser')
for item1 in soup.select('.coin-icon img'):
link = item1.get('data-src').replace('thumb', 'thumb_2x')
with open(basename(link), "wb") as f:
f.write(requests.get(link).content)
但是,我需要保存图像,其名称与 CoinGecko 列表中硬币的代码相同(将 bitcoin.png?1547033579 重命名为 BTC.png,ethereum.png?1595348880 重命名为 ETH.png,等等) .需要重命名的图像超过 7000 张,其中许多具有非常独特的名称,因此切片在这里不起作用。
有什么办法呢?
【问题讨论】:
-
所以你问如何将
bitcoin.png?1547033579重命名为Bitcoin.png?basename(link).split('?')[0].upper() -
我编辑了 OP,所以它更有意义
标签: python web-scraping beautifulsoup python-requests screen-scraping