【问题标题】:Python web scraping : how to skip url errorPython网页抓取:如何跳过url错误
【发布时间】:2020-02-16 01:20:33
【问题描述】:

我正在尝试抓取网页(“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 不存在。我不知道如何跳过这些。你能帮帮我吗?

【问题讨论】:

  • 使用tryexcept 处理异常,编写在tryexcept 异常中引发错误的部分,并且什么都不做,写pass to ignore except 或者你可以编写代码当出现错误时会做一些事情
  • 你能举一个有效的 url 和失败的 url 的例子吗?

标签: python beautifulsoup web-crawler screen-scraping


【解决方案1】:

使用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')

【讨论】:

    【解决方案2】:

    使用错误捕获。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-29
      • 2021-02-25
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多