Python网页抓取:如何跳过

2024-09-30 03:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图刮一个网页(“coinmarketcap”)。我正在搜集2013年至2019年10月所有加密货币的数据(开盘、高点、低点、收盘、市值、成交量)。你知道吗

for j in range (0,name_size):
   url = ("https://coinmarketcap.com/currencies/" + str(name[j]) + "/historical-data/?start=20130429&end=20191016")
   page = urllib.request.urlopen(url)

   soup = BeautifulSoup(page, 'html.parser')

   priceDiv = soup.find('div', attrs={'class':'table-responsive'})
rows = priceDiv.find_all('tr')

问题是某个url不存在。我不知道如何跳过这些。你能帮帮我吗?你知道吗


Tags: 数据nameurl网页page货币findsoup
2条回答

使用错误捕获。你知道吗

try: 
    #do the thing
except Exception as e:
    #here you can print the error

出错的将被打印消息跳过,否则任务将继续

使用try-except

for j in range (0,name_size):
   url = ("https://coinmarketcap.com/currencies/" + str(name[j]) + "/historical-data/?start=20130429&end=20191016")
   try: 
       page = urllib.request.urlopen(url)
       soup = BeautifulSoup(page, 'html.parser')
       priceDiv = soup.find('div', attrs={'class':'table-responsive'})
   except:
       print("Coult not open url")

rows = priceDiv.find_all('tr')

相关问题 更多 >

    热门问题