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

时间:2017-01-21 14:57:16

标签: python

在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_access_token是我从facebook图形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

我只想获取我的Facebook信息,例如我的朋友和喜欢。在Graph API Explorer上它非常成功,但是当我尝试编写Python程序时,它总是出错。

1 个答案:

答案 0 :(得分:0)

如果您在使用错误的网址时出现此类问题,请尝试此操作。

解决方案:

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")

希望这个帮助完整。