Search code examples
pythonjsonregexinstagram-api

Finding the exact match of many usernames stored in a variable while looping


I have a code which sends usernames from an excel sheet as an input which is stored in a variable xy to an instagram API which in return gives the results. I load the URL to a JSON to get it in a json schema.

For example when my variable xy contains "shawn_123" the result from the API is:

{
"meta":  {
"code": 200
},
"data":  [
 {
  "username": "shawn_123",
  "profile_picture": "https://scontent.cdninstagram.com/t51.2885-  19/s150x150/11417456_1610194859266611_592197892_a.jpg",
  "id": "641567093",
  "full_name": "shawn ritz"
},
 {
  "username": "shawn_12345",
  "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/11324946_808347519273018_2073555780_a.jpg",
  "id": "2074312361",
  "full_name": "shawney"
}
]
}

And my code is

for r in range(1,10):
var=r,sheet.cell(row=r,column=1).value
xy=var[1]
myopener=Myopener()
url=myopener.open('https://api.instagram.com/v1/users/search?q='+xy+'&count=1&access_token=641567093.1fb234f.a0ffbe574e844e1c818145097050cf33')
beta=json.load(url)
for item in beta['data']:
    print(item['id'])

As it is retrieving two outputs from a same username.

Note: I want a regular expression which searches the exact username from the json and save the user_id of only that record.


Solution

  • You can check if the username matches before printing the id:

    for item in beta['data']:
        if item['username'] == xy: # here check the username from your input
            print(item['id'])
    

    Or, using next operator:

    user_id = next((item['id'] for item in beta['data'] if item['username'] == xy), None)