Convert user ID to username
(browser, user_id, logger)
| 1874 | |
| 1875 | |
| 1876 | def get_username_from_id(browser, user_id, logger): |
| 1877 | """Convert user ID to username""" |
| 1878 | # method using graphql 'Account media' endpoint |
| 1879 | logger.info("Trying to find the username from the given user ID by loading a post") |
| 1880 | |
| 1881 | query_hash = "42323d64886122307be10013ad2dcc44" # earlier- |
| 1882 | # "472f257a40c653c64c666ce877d59d2b" |
| 1883 | graphql_query_URL = "https://www.instagram.com/graphql/query/?query_hash={}".format( |
| 1884 | query_hash |
| 1885 | ) |
| 1886 | variables = {"id": str(user_id), "first": 1} |
| 1887 | post_url = "{}&variables={}".format(graphql_query_URL, str(json.dumps(variables))) |
| 1888 | |
| 1889 | web_address_navigator(browser, post_url) |
| 1890 | try: |
| 1891 | pre = browser.find_element(By.TAG_NAME, "pre").text |
| 1892 | except NoSuchElementException: |
| 1893 | logger.info("Encountered an error to find `pre` in page, skipping username.") |
| 1894 | return None |
| 1895 | user_data = json.loads(pre)["data"]["user"] |
| 1896 | |
| 1897 | if user_data: |
| 1898 | user_data = user_data["edge_owner_to_timeline_media"] |
| 1899 | |
| 1900 | if user_data["edges"]: |
| 1901 | post_code = user_data["edges"][0]["node"]["shortcode"] |
| 1902 | post_page = "https://www.instagram.com/p/{}".format(post_code) |
| 1903 | |
| 1904 | web_address_navigator(browser, post_page) |
| 1905 | username = get_username(browser, "post", logger) |
| 1906 | if username: |
| 1907 | return username |
| 1908 | |
| 1909 | else: |
| 1910 | if user_data["count"] == 0: |
| 1911 | logger.info("Profile with ID {}: no pics found".format(user_id)) |
| 1912 | |
| 1913 | else: |
| 1914 | logger.info( |
| 1915 | "Can't load pics of a private profile to find username (" |
| 1916 | "ID: {})".format(user_id) |
| 1917 | ) |
| 1918 | |
| 1919 | else: |
| 1920 | logger.info( |
| 1921 | "No profile found, the user may have blocked you (ID: {})".format(user_id) |
| 1922 | ) |
| 1923 | return None |
| 1924 | |
| 1925 | """ method using private API |
| 1926 | #logger.info("Trying to find the username from the given user ID by a |
| 1927 | quick API call") |
| 1928 | |
| 1929 | #req = requests.get(u"https://i.instagram.com/api/v1/users/{}/info/" |
| 1930 | # .format(user_id)) |
| 1931 | #if req: |
| 1932 | # data = json.loads(req.text) |
| 1933 | # if data["user"]: |
no test coverage detected