Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python requests.exceptions.MissingSchema:无效的URL'';没有提供架构_Python - Fatal编程技术网

Python requests.exceptions.MissingSchema:无效的URL'';没有提供架构

Python requests.exceptions.MissingSchema:无效的URL'';没有提供架构,python,Python,在FBCrwal.py中 user_id = "110286969468305" u_access_token = "EAACEdEose0cBAAkwvOQkWQ8x8EMpZCaii7Azfmsmhz96GEOZBaMnnjUsGswL8Y4VlT5lMd2QzfO2JmNS8p1suYmfgVJ5DSs33lxATp21WxbFZAKKMoveuRJffOLp0hTg2ka2ZAVuXsacGAkcJtgBd92urglZCwQ43FyKMqoDKaLiSBZA5mvs65iC6Fyzms

在FBCrwal.py中

user_id = "110286969468305"
u_access_token = "EAACEdEose0cBAAkwvOQkWQ8x8EMpZCaii7Azfmsmhz96GEOZBaMnnjUsGswL8Y4VlT5lMd2QzfO2JmNS8p1suYmfgVJ5DSs33lxATp21WxbFZAKKMoveuRJffOLp0hTg2ka2ZAVuXsacGAkcJtgBd92urglZCwQ43FyKMqoDKaLiSBZA5mvs65iC6FyzmsNb9We1gJCsAVXQZDZD"
user_info_type = "user_friends"
user_info_download.get_user_info(user_id,user_info_type,u_access_token)
这个u_访问标志是我从facebook graph API Explorer复制的

在user_infor_download.py中:

def get_user_info(user_id,info_type,u_access_token = None):

    if info_type == "user_friends":
        params = r"friends"
    elif info_type == "user_likes":
        params = r"likes"
    elif info_type == "user_feed":
        params = r"feed?   

    fields=permalink_url,from,story,type,message,link,created_time,updated_time,likes.limit(0).summary(total_count),comments.limit(0).summary(total_count)"

    # To get the access token
    if u_access_token:
        FB_access_token = u_access_token
    else:
        FB_access_token = get_access_token.get_fb_token(glovar.APP_ID,    glovar.APP_SECRET)

    graph = facebook.GraphAPI(FB_access_token)
    # profile = graph.get_object(public_figure_name)
    user_info = graph.get_connections(user_id, params)

    if "Error" in user_info:
        print("Error", user_info["Error"]["message"])
        return []

    user_info_data = []
    while(user_info["data"]):
        if "Error" in user_info:
            print("Error", user_info["Error"]["message"])
            return []
    if "data" in user_info:
        try:
            for user_info_item in user_info["data"]:
                if info_type == "user_feed":
                    # Convenience:Add empty field for message/link if not existent
                    user_info_item["message"] = user_info_item["message"] if "message" in user_info_item else ""
                    user_info_item["link"] = user_info_item["link"] if "link" in user_info_item else ""
                user_info_data.append(user_info_item)
            if info_type == "user_friends" or "user_likes":
                user_info = requests.get(user_info["paging"]["cursors"]["after"]).json()
            elif info_type == "user_feed":
                user_info = requests.get(user_info["paging"]["next"]).json()
        except KeyError:
            break

    print(user_info_data)
在facebook.py中:

class  GraphAPI(object):
    def __init__(self,access_token = None, timeout = None, version = None,proxies = None, session = None):
        #The default version is only used if the version kwarg does not exist
        default_version = VALID_API_VERSIONS[0]

        self.access_token = access_token
        self.timeout = timeout
        self.proxies = proxies
        self.session = session or requests.session()

        if version:
            version_regex = re.compile("^\d\.\d$")
            match = version_regex.search(str(version))
            if match is not None:
                if str(version) not in VALID_API_VERSIONS:
                    raise GraphAPIError("Valid API versions are " + str(VALID_API_VERSIONS).strip("[]"))
                else:
                    self.version = "v" + str(version)
            else:
                raise GraphAPIError("Version number should be in the following format:#.#(e.r.,2.0).")
        else:
            self.version = "v" + default_version


    def get_connections(self,id,connection_name,**args):
        '''Fetch the connections for given object'''
        return self.request("{0}/{1}/{2}".format(self.version,id,connection_name),args)


def request(self,path,args = None,post_args = None,files = None,method = None):
    '''Fetches the given path in the Graph API

    We translate args to a valid query string.If post_args is
    given, we send a POST request to the given path with the given
    arguments
    :param path:
    :param args:
    :param post_args:
    :param files:
    :param method:
    :return:
    '''
    if args is None:
        args = dict()
    if post_args is not None:
        method = "POST"

    #Add 'access_token' to post_args or args if it has not already been
    #included
    if self.access_token:
        #If post_args exists,we assume that args either does not exists
        #or it does not need "access_token"
        if post_args and "access_token" not in post_args:
            post_args["access_token"] = self.access_token
        elif "access_token" not in args:
            args["access_token"] = self.access_token

    try:
        response = self.session.request(
            method or "GET",
            FACEBOOK_GRAPH_URL + path,
            timeout = self.timeout,
            params = args,
            data = post_args,
            proxies = self.proxies,
            files = files
        )
    except requests.HTTPError as e:
        response = json.loads(e.response)
        raise GraphAPIError(response)

    headers = response.headers
    if "json" in headers['content-type']:
        result = response.json()
    elif "image/" in headers['content-type']:
        mimetype = headers['content-type']
        result = {"data":response.content,
                  "mime-type":mimetype,
                  "url":response.url}
    elif "access_token" in parse_qs(response.text):
        query_str = parse_qs(response.text)
        if "access_token" in query_str:
            result = {"access_token":query_str["access_token"][0]}
            if "expires" in query_str:
                result["expires"] = query_str["expires"][0]
        else:
            raise GraphAPIError(response.json())
    else:
        raise GraphAPIError("Maintype was not text,image,or querystring")


    if result and isinstance(result,dict) and result.get("error"):
        raise GraphAPIError(result)

    return result
运行时,会出现以下错误:

Traceback (most recent call last):
  File "C:/Python/PyCharmProject/FaceBookCrawl/FBCrawl.py", line 253, in <module>
    user_info_download.get_user_info(user_id,user_info_type,u_access_token)
  File "C:\Python\PyCharmProject\FaceBookCrawl\user_info_download.py", line 50, in get_user_info
   user_info = requests.get(user_info["paging"]["cursors"]["after"]).json()
  File "C:\Python\Python36\lib\site-packages\requests\api.py", line 70, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Python\Python36\lib\site-packages\requests\api.py", line 56, in request
   return session.request(method=method, url=url, **kwargs)
  File "C:\Python\Python36\lib\site-packages\requests\sessions.py", line 474, in request
    prep = self.prepare_request(req)
  File "C:\Python\Python36\lib\site-packages\requests\sessions.py", line 407, in prepare_request
   hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Python\Python36\lib\site-packages\requests\models.py", line 302, in prepare
    self.prepare_url(url, params)
  File "C:\Python\Python36\lib\site-packages\requests\models.py", line 366, in prepare_url
    raise MissingSchema(error)
  requests.exceptions.MissingSchema: Invalid URL 'QVFIUlNtXzlmLVNnaUZAoaWpwMDdUOFVVcGt5QmFTY0x1ZAHFZAT1hsVDdkeHZARQTg4aVY3VWFfR1U3aFVfalV4YXpEQWFxNjFwbWRNdVpxMnVtQTNXa3FnZAS1B': No schema supplied. Perhaps you meant     

   http://QVFIUlNtXzlmLVNnaUZAoaWpwMDdUOFVVcGt5QmFTY0x1ZAHFZAT1hsVDdkeHZARQTg4aVY3VWFfR1U3aFVfalV4YXpEQWFxNjFwbWRNdVpxMnVtQTNXa3FnZAS1B?
Process finished with exit code 1
回溯(最近一次呼叫最后一次):
文件“C:/Python/PyCharmProject/FaceBookCrawl/FBCrawl.py”,第253行,在
用户信息下载。获取用户信息(用户id、用户信息类型、用户访问令牌)
文件“C:\Python\PyCharmProject\FaceBookCrawl\user\u info\u download.py”,第50行,在get\u user\u info中
user_info=requests.get(user_info[“paging”][“cursors”][“cursors”][“after”]).json()
get中第70行的文件“C:\Python\Python36\lib\site packages\requests\api.py”
返回请求('get',url,params=params,**kwargs)
请求中第56行的文件“C:\Python\Python36\lib\site packages\requests\api.py”
return session.request(method=method,url=url,**kwargs)
文件“C:\Python\Python36\lib\site packages\requests\sessions.py”,第474行,在请求中
准备=自我准备请求(req)
文件“C:\Python\Python36\lib\site packages\requests\sessions.py”,第407行,在prepare\u请求中
钩子=合并钩子(request.hooks,self.hooks),
文件“C:\Python\Python36\lib\site packages\requests\models.py”,第302行,在prepare中
self.prepare_url(url,参数)
文件“C:\Python\Python36\lib\site packages\requests\models.py”,第366行,在prepare\u url中
raise MissingSchema(错误)
requests.exceptions.MissingSchema:无效URL“qvfiulntxzlmlvnnauzaoawpwmddu of vvgcgt5qmfty0x1zahfzat1hsvddkehzarqtg4avy3vwfffr1u3afvffalv4yxpeqwfxnjfwwrndvtpxmnvtnqtnxa3fnza1b”:未提供架构。也许你的意思是
http://QVFIUlNtXzlmLVNnaUZAoaWpwMDdUOFVVcGt5QmFTY0x1ZAHFZAT1hsVDdkeHZARQTg4aVY3VWFfR1U3aFVfalV4YXpEQWFxNjFwbWRNdVpxMnVtQTNXa3FnZAS1B?
进程已完成,退出代码为1

我只想获得我的facebook信息,比如我的朋友和喜欢的人。在Graph API Explorer上,这是非常成功的,但是当我尝试编写Python程序来执行此操作时,总是会出错。

如果您在使用错误的URL时遇到此类问题,请尝试此方法

解决方案:

import requests

correct_url = False
url = 'Ankit Gandhi' # 'https://gmail.com'
try:
    res = requests.get(url)
    correct_url = True
except:
    print("Please enter a valid URL")
if correct_url:
    """
     Do your operation
    """
    print("Correct URL")
希望这对你有帮助