urllib2.URLError:<urlopen error =“”unknown =“”url =“”type:=“”webcal =“”>尝试编写.ics文件时

时间:2017-07-10 23:32:09

标签: python html

我正在尝试将日历(.ics)的内容从网页(例如https://careers.unc.edu/calendar)写入文件。以下是我的代码尝试:

def write_file(ics_url, set_calendar_name):

    url = ics_url

    response = urllib2.urlopen(url)
    webContent = response.read()

    f = open(set_calendar_name, 'w')
    f.write(webContent)
    f.close

    print 'File saved as: ' + set_calendar_name
    print
    return set_calendar_name

但是,我一直收到以下错误:

Traceback (most recent call last):
File "get_calendar.py", line 99, in <module>
  write_file(get_ics_url('https://careers.unc.edu/calendar'), 'carolina.ics')
File "get_calendar.py", line 36, in write_file
  response = urllib2.urlopen(url)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
  return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 429, in open
  response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 452, in _open
  'unknown_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 407, in _call_chain
  result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1266, in unknown_open
  raise URLError('unknown url type: %s' % type)
urllib2.URLError: <urlopen error unknown url type: webcal>

有没有人对我的代码中导致它的原因有任何想法?当我运行它时,我的程序正常运行,例如,这个URL:https://meded.hms.harvard.edu/calendar但不是前面提到的那个。

1 个答案:

答案 0 :(得分:0)

解决方案:我最终弄清楚出了什么问题。在

link.get('href')

包含

'webcal:'

而不是

'https:' 

一开始,所以我不得不更换它。固定代码应为:

if link.get('href') != None and '.ics' in link.get('href'):
        endout = link.get('href')

        if endout[:6] == 'webcal':
            endout ='https' + endout[6:]