我正在尝试向远程网页发出Get方法请求,并根据请求发送标头。我的请求获得了正确的标头值和cookie,但是当我运行此代码时,我不断收到以下错误:
任何人都可以告诉我如何解决此错误并提出正确的Get方法请求吗?我应该导入我缺少的任何图书馆吗?提前致谢。
代码:
import urllib,urllib2,re,xbmcplugin,xbmcgui,sys,os,xbmc,xbmcaddon
import cookielib,requests,json
import requests
def myfunction(url):
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
resp = opener.open(url)
resp2 = opener.open('http://www.awebsite.com/test/api.php')
html_data = resp2.read()
pattern = re.compile('"X-hello-data",\s?"(.*?)"')
xhellodata = pattern.search(html_data).groups()[0]
myheaders = {'Cookie' : cookies, 'User-Agent' : 'XBMC', 'Referer' : 'http://www.awebsite.com/main.php', 'X-hello-data' : xhellodata}
itemurl = 'http://www.awebsite.com/ajax.php?season=winter&type=2&name=test'
r = http.request('GET', itemurl, headers=myheaders)
print r;
itemurl2 = urllib.unquote(r.data)
print 'valueofItemUrl2'
print itemurl2;
错误:
ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.NameError'>
Error Contents: global name 'http' is not defined
Traceback (most recent call last):
File "f:\......\addon.py", line 703, in <module>
myfunction(url)
File "f:\.....\addon.py", line 636, in myfunction
r = http.request('GET', itemurl, headers=myheaders)
NameError: global name 'http' is not defined
-->End of Python script error report<--
答案 0 :(得分:-1)
您在所有混乱中遇到的错误是
全球名称&#39; http&#39;未定义
如果你查看代码,你永远不会在任何地方初始化http,所以当你试图在行中使用它时,它显然是一个未定义的变量:
r = http.request('GET', itemurl, headers=myheaders)
我建议您使用requests
进行GET
r = requests.get(itemurl, headers=myheaders, cookies=cj)
print(r.text)
然后,您可以按照自己的方式解析响应。
我个人会专门针对您尝试做的事情使用请求(未经过测试,因为您没有发布真实的网址)。
import requests
import json
cj = cookielib.CookieJar()
response = requests.get('http://www.awebsite.com/test/api.php', cookies=cj)
xhellodata = response.headers.get('X-hello-data')
myheaders = {'Cookie' : cookies, 'User-Agent' : 'XBMC', 'Referer' : 'http://www.awebsite.com/main.php', 'X-hello-data' : xhellodata}
itemurl = 'http://www.awebsite.com/ajax.php?season=winter&type=2&name=test'
response = requests.get(itemurl, headers=myheaders, cookies=cj)
data = json.loads(response.text)