我需要从python脚本调用一个Url

时间:2017-09-27 18:34:27

标签: python raspberry-pi

我的搜索找到了更复杂的网址调用的解决方案,但我找不到一个简单的。

我有这个设置:轴IP扬声器和rasperry pi。几个按钮连接到rasperry的GPIO,按下时应通过一个简单的URL触发轴扬声器上的音频文件

示例 http://192.168.10.204/axis-cgi/playclip.cgi?location=emergency.mp3&repeat=0&volume=22

通过在浏览器中输入此URL,扬声器在第22卷播放文件emergency.mp3

现在我开始整理剧本

import RPi.GPIO as GPIO
import time
import urllib
import sys
import os

GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

while(True):
    if (GPIO.input (11) == True):
        response = urllib.urlopen('http://192.168.10.204/axis-cgi/playclip.cgi?location=emergency.mp3&repeat=0&volume=22').read()

当我按下按钮时,这就是我得到的

Traceback (most recent call last):
  File "axis.py", line 13, in <module>
    response = urllib.urlopen('http://192.168.10.204/axis-cgi/playclip.cgi?location=emergency.mp3&repeat=0&volume=22').read()
  File "/usr/lib/python2.7/urllib.py", line 87, in urlopen
    return opener.open(url)
  File "/usr/lib/python2.7/urllib.py", line 213, in open
    return getattr(self, name)(url)
  File "/usr/lib/python2.7/urllib.py", line 364, in open_http
    return self.http_error(url, fp, errcode, errmsg, headers)
  File "/usr/lib/python2.7/urllib.py", line 377, in http_error
    result = method(url, fp, errcode, errmsg, headers)
  File "/usr/lib/python2.7/urllib.py", line 701, in http_error_401
    errcode, errmsg, headers)
  File "/usr/lib/python2.7/urllib.py", line 386, in http_error_default
    raise IOError, ('http error', errcode, errmsg, headers)
IOError: ('http error', 401, 'Unauthorized', <httplib.HTTPMessage instance at 0x7669f738>)

1 个答案:

答案 0 :(得分:0)

如果您使用的网站需要用户代理,如果不是您的用户代理,那么您需要指定用户代理,例如: `

url='YOUR URL'
headers={}
headers['User-Agent']='Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17'
req=urllib.request.Request(url, headers=headers)
resp=urllib.request.urlopen(req)
data=resp.read()

`