Image

Imageunixblog wrote in Imageru_python

Проблемы с urllib2

Учу Python, наступаю на грабли, прошу помощи.

Пишу плагин для Nagios'а. Более того -- он даже работает, но функцию с urllib2 я реализовал неправильно, по ходу.

Так работает:
# python /usr/local/nagios/libexec/check_dell.py
OK - 725 days remaining (start: 2007-9-3 end: 2012-9-3)


А так нет:
# su nagios -c /usr/local/nagios/libexec/check_dell.py
Traceback (most recent call last):
    File "/usr/local/nagios/libexec/check_dell.py", line 72, in ?
        data = check_dell().split(',')
    File "/usr/local/nagios/libexec/check_dell.py", line 23, in check_dell
        page = urllib2.urlopen(url % (tag,))
    File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen
        return _opener.open(url, data)
    File "/usr/lib/python2.4/urllib2.py", line 364, in open
        response = meth(req, response)
    File "/usr/lib/python2.4/urllib2.py", line 471, in http_response
        response = self.parent.error(
    File "/usr/lib/python2.4/urllib2.py", line 402, in error
        return self._call_chain(*args)
    File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain
        result = func(*args)
    File "/usr/lib/python2.4/urllib2.py", line 480, in http_error_default
        raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 406: Not Acceptable



Собственно, функция:
tag = 'JL3S33J'

def check_dell():
  url = 'http://support.dell.com/support/topics/global.aspx/support/my_systems_info/details?c=us&l=en&s=gen&ServiceTag=%s'
  new_date = re.compile("(\d{1,2})\/(\d{1,2})\/(\d{4})")
  page = urllib2.urlopen(url % (tag,))
  soup = BeautifulSoup(page.read())

  table = soup.find('table',{'class':"contract_table"})
  rows = table.findAll('tr')
  rows = rows[1:]

  for row in rows:
    output = "%s" % (tag,)
    cells = row.findAll('td')
    for cell in cells:
        if cell.a:
            txt = cell.a.string
        elif cell.b:
            txt = cell.b.string
        elif cell.i:
            txt = cell.i.string
        else:
            txt = cell.string

        match = new_date.search(txt)
        if match:
          txt = "%d-%d-%d" % (int(match.group(3)),int(match.group(1)),int(match.group(2)))
        output = "%s,%s" % (output,txt)
  return output