urllib2错误“在加速器上找不到”

2024-10-01 13:33:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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)

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


Tags: fromimportadafruittime错误sleepvalurllib2
1条回答
网友
1楼 · 发布于 2024-10-01 13:33:00

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

尽管它们解析为同一个主机(206.190.43.214,很明显),URL中实际的名称最终会作为HTTP请求中的Host:报头。你可以看出,这一点很重要:

$ 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地址:

^{pr2}$

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

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)

一旦修复了这个问题,代码中至少还有一个问题。当mdata是一个urlopen时,不能调用minidom.parseString(mdata);您需要对该对象调用read(),或者使用parse代替{}。在

相关问题 更多 >