python - urllib2错误 'Not found on Accelerator'

标签 python api http-status-code-404 urllib weather-api

我有一个 python 程序,定期从 weather.yahooapis.com 检查天气,但它总是抛出错误:urllib.HTTPError: HTTP Error 404: Not Found on Accelerator。我在两台不同的计算机上尝试过,但没有成功,并且还更改了我的 DNS 设置。我继续收到错误。这是我的代码:

#!/usr/bin/python

import time
#from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
from xml.dom import minidom
import urllib2

#towns, as woeids
towns = [2365345,2366030,2452373]

val = 1
while val == 1:
time.sleep(2)
for i in towns:
    mdata = urllib2.urlopen('http://206.190.43.214/forecastrss?w='+str(i)+'&u=f')
    sdata = minidom.parseString(mdata)
    atm = sdata.getElementsByTagName('yweather:atmosphere')[0]
    current = sdata.getElementsByTagName('yweather:condition')[0]
    humid = atm.attributes['humidity'].value
    tempf = current.attributes['temp'].value
    print(tempf)
    time.sleep(8)

我可以在出现错误的同一台计算机上通过网络浏览器成功访问 API 的输出。

最佳答案

问题在于您使用的是 IP 地址 206.190.43.214,而不是主机名 weather.yahooapis.com

即使它们解析为同一主机(显然是 206.190.43.214),URL 中实际的名称最终会作为 HTTP 中的 Host: header 要求。您可以看出这在这里产生了差异:

$ curl 'http://206.190.43.214/forecastrss?w=2365345&u=f'
<404 error>
$ curl 'http://weather.yahooapis.com/forecastrss?w=2365345&u=f'
<correct rss>
$ curl 'http://206.190.43.214/forecastrss?w=2365345&u=f' -H 'Host: weather.yahooapis.com'
<correct rss>

如果您在浏览器中测试这两个 URL,您会看到相同的结果。

<小时/>

因此,在您的代码中,您有两个选择。您可以使用 DNS 名称而不是 IP 地址:

mdata = urllib2.urlopen('http://weather.yahooapis.com/forecastrss?w='+str(i)+'&u=f')

...或者您可以使用 IP 地址并手动添加主机 header :

req = urllib2.Request('http://206.190.43.214/forecastrss?w='+str(i)+'&u=f')
req.add_header('Host', 'weather.yahooapis.com')
mdata = urllib2.urlopen(req)
<小时/>

修复此问题后,您的代码中至少存在一个其他问题。当 mdataurlopen 时,你不能调用 minidom.parseString(mdata);您需要在该事物上调用 read(),或者使用 parse 而不是 parseString

关于python - urllib2错误 'Not found on Accelerator',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19149381/

相关文章:

python - cron 作业没有将输出写入正确的输出日志文件

deployment - GlassFish 3.1.2 在部署时给出 404,没有任何错误

url - IS 将查询字符串中的双斜杠修改为单斜杠

python - 解析内部为空元素的元素的文本

Python3 urllib.request 不会立即关闭连接

api - 超过 Google Geocode API 使用限制后如何解锁?

java - 如何在 Android 上使用 Google Maps Directions API?

asp.net - IIS7 404错误

python - 如何在服务器上通过web启动特权进程?

javascript - Javascript 中的 Google Cloud Function 在函数完成之前完成