This is for an internal project. My end goal is to get details of my connections. who are in same city as I am.
I am new in using LinkedIn API . I have used code mentioned in answer here to generate the access token. Now I am using below line to get my LinkedIn profile.
application.get_profile(access_token['oauth_token'])
But I am getting below error.
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
application.get_profile(access_token['oauth_token'])
File "C:\Python34\lib\site-packages\python_linkedin-2.0-py3.4.egg\linkedin\linkedin.py", line 189, in get_profile
response = self.make_request('GET', url, params=params, headers=headers)
File "C:\Python34\lib\site-packages\python_linkedin-2.0-py3.4.egg\linkedin\linkedin.py", line 169, in make_request
params.update({'oauth2_access_token': self.authentication.token.access_token})
AttributeError: 'str' object has no attribute 'token'
Can someone please help me?
It is a bit late I guess. But for future reference, this error comes from the fact that you need to call explicitly the token element from the linkedin application.
For instance, to generate the application, you need to enter the following:
from linkedin_v2 import linkedin
application = linkedin.LinkedInApplication(token=access_token['oauth_token'])
From there, you can then call the different function from application (like "application.get_profile()").
BR
I don't think you need to pass the auth token again to get your profile. I am also using the python lib.
application.get_profile()
Should return the basic information for your profile. Then look into using selectors to specify what endpoints you want.
Related
Trying to store/re-use cookies between code-executions, similar to this question, but using only python3's urllib.
Thanks to this answer for the process for creating a cookiejar for automatic use across urllib.request.Request calls:
cookie_jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie_jar))
urllib.request.install_opener(opener)
Initial searches on cookie storage led to SO questions regarding requests (the module) + cookies, but unfortunately, http.cookiejar objects cannot be pickled (below), as opposed to their requests brethren, which can:
>>> pickle.dumps(cookie_jar)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't pickle _thread.RLock objects
The other queries' results mostly pointed back the python3 docs: https://docs.python.org/3/library/http.cookiejar.html#http.cookiejar.FileCookieJar
Playing around with the FileCookieJar class led to noticing in the description: A CookieJar which can load cookies from, and *perhaps* save cookies to, a file on disk. and the associated error:
>>> FCJ=cookiejar.FileCookieJar("unversioned.cookies")
>>> FCJ.save()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.7/http/cookiejar.py", line 1785, in save
raise NotImplementedError()
Both of which were clarified by this answer - which suggested using LWPCookieJar (among others) instead, but I couldn't find any existing examples on how to use this class in practice.
LWPCookieJar was the answer:
Create the CookieJar + try loading from any existing cookie file:
cookie_filename = "unversioned.cookies"
cookie_jar = cookiejar.LWPCookieJar(cookie_filename)
try:
cookie_jar.load()
except FileNotFoundError as fnfe:
# No existing/adjacent cookie file
pass
opener = request.build_opener(request.HTTPCookieProcessor(cookie_jar))
request.install_opener(opener)
complete any urllib.request.Request call that populates cookies
store the cookies to file (named in the constructor):
cookie_jar.save()
And to confirm, after having saved some cookies in a previous execution-run:
prepare the cookiejar, but do not call .load()
test-request the page -> logged-out version received
call cookiejar.load()
test-request the page -> logged-in version received
I'm trying to use the example program provided by Microsoft here to test out the Bing Image Search Service associated with their Cognitive Service offering on Azure. I type the code in character by character (of course, using my own API key) and I get the below error message when I execute the program:
Traceback (most recent call last):
File "x.py", line 9, in <module>
image_results = client.images.search(query=search_term)
File "/home/rsbrownjr/anaconda3/envs/ibing/lib/python3.6/site-packages/azure/cognitiveservices/search/imagesearch/operations/images_operations.py", line 485, in search
raise models.ErrorResponseException(self._deserialize, response)
azure.cognitiveservices.search.imagesearch.models.error_response_py3.ErrorResponseException: Operation returned an invalid status code 'PermissionDenied'
I know without a doubt that I have the right API key put into the program. I'm on pricing tier S0 pay-as-you-go but I don't have any other options either. This has got to have a simple solution.
from azure.cognitiveservices.search.imagesearch import ImageSearchAPI
from msrest.authentication import CognitiveServicesCredentials
subscription_key = "MY API KEY HERE"
search_term = "canadian rockies"
client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
image_results = client.images.search(query=search_term)
if image_results.value:
first_image_result = image_results.value[0]
print("Total number of images returned: {}".format(len(image_results.value)))
print("First image thumbnail url: {}".format(
first_image_result.thumbnail_url))
print("First image content url: {}".format(first_image_result.content_url))
else:
print("No image results returned!")
I just tested the code, the code is fine. So you must provided the wrong API key.
Here is my test key 52c32221ceaa4f388b26a2b85fb79bff. It is a 7 days free trial key. I got it here.
I tried to login into the site through RoboBrowser but I'm facing below error.
import config
from robobrowser import RoboBrowser
br = RoboBrowser()
br.open('https://stackoverflow.com')
form = br.get_form(id="login-form")
form['Email address']=config.username
form['Password']=config.password
br.submit_form(form)
Error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\test\AppData\Local\Programs\Python\Python37\lib\site-packages\robobrowser\forms\form.py", line 216, in __setitem__
self.fields[key].value = value
File "C:\Users\test\AppData\Local\Programs\Python\Python37\lib\site-packages\werkzeug\datastructures.py", line 784, in __getitem__
raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
Through any other module, we are able to login into site and search data in the next screen. Example if I login into site and next page it will display as "Hello User".
I want to bring the output and see "Hello User" is displayed or not through the python script
I think you are trying to login to the sing up form. Move to the login page and then login.
import config
from robobrowser import RoboBrowser
br = RoboBrowser()
br.open('https://stackoverflow.com/users/login')
form = br.get_form(id="login-form")
form['email']=config.username
form['password']=config.password
br.submit_form(form)
This error, surprisingly, would happen if you are setting a form field which is not actually a part of the form. Tomasz's answer goes to the point of what was wrong, but a couple additional notes:
robobrowser is not supported and you should look into better-maintained libraries like MechanicalSoup or mechanize
StackExchange has an API
I am trying to convert audio to text using Google Cloud Speech API, but I am getting the following error:
Traceback (most recent call last):
File "/home/prateek/Google Drive/projects/linuxAI/src/linuxAI.py", line 6, in <module>
client = speech.SpeechClient()
File "/usr/lib/python3.6/site-packages/google/cloud/gapic/speech/v1/speech_client.py", line 146, in __init__
ssl_credentials=ssl_credentials)
File "/usr/lib/python3.6/site-packages/google/gax/grpc.py", line 106, in create_stub
credentials = _grpc_google_auth.get_default_credentials(scopes)
File "/usr/lib/python3.6/site-packages/google/gax/_grpc_google_auth.py", line 62, in get_default_credentials
credentials, _ = google.auth.default(scopes=scopes)
File "/usr/lib/python3.6/site-packages/google/auth/_default.py", line 283, in default
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application. For more
information, please see
https://developers.google.com/accounts/docs/application-default-credentials.
I am using this code:
"""Transcribe the given audio file."""
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
client = speech.SpeechClient()
speech_file = "output.wav"
with open(speech_file, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code='en-US')
response = client.recognize(config, audio)
# Each result is for a consecutive portion of the audio. Iterate through
# them to get the transcripts for the entire audio file.
for result in response.results:
# The first alternative is the most likely one for this portion.
print('Transcript: {}'.format(result.alternatives[0].transcript))
I found tutorial from here.
Did you authenticated using credentials?
First you need to create api keys.
https://support.google.com/cloud/answer/6158862?hl=en
Read this tutorial to authenticate.
https://cloud.google.com/speech/docs/auth
You can see some sample applications provided by Google.
https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/speech/cloud-client
Here is my code:
from robobrowser import browser
url = 'http://diesel.elcat.kg/index.php?act=Login&CODE=00'
url3 = 'http://diesel.elcat.kg/index.php?act=post&do=reply_post&f=178&t=233500064'
m = browser.RoboBrowser()
m.open(url)
# SIGNING IN(form1)
form1 = m.get_form(action='https://diesel.elcat.kg/index.php?act=Login&CODE=01')
form1['UserName'].value = 'Username'
form1['PassWord'].value = 'Password'
m.submit_form(form1)
# FINISHED SIGNING IN(everything worked)
# GOING TO THE PAGE WHERE FORM IS LOCATED
m.open(url3)
# Can't submit this form
form2 = m.get_form(action="http://diesel.elcat.kg/index.php?")
form2['Post'].value = 'up'
m.submit_form(form2)
I can sign in to the website so form1 works, but when I try in this case leave a comment(up), form2 does not work.I am keep getting either InvalidSubmit error either Bad Request error. Code of form1 and code of form2 seem to be the same, but one works and another does not. I am using python3.5 and robobrowser, and I am using Mac OS if that's gonna help. Thank you in advance.
Here is my traceback:
Traceback (most recent call last):
File "/Users/bkkadmin/Desktop/Daniiar/upper/test2.py", line 18, in <module>
m.submit_form(form)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/robobrowser-0.5.3-py3.5.egg/robobrowser/browser.py", line 339, in submit_form
payload = form.serialize(submit=submit)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/robobrowser-0.5.3-py3.5.egg/robobrowser/forms/form.py", line 226, in serialize
include_fields = prepare_fields(self.fields, self.submit_fields, submit)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/robobrowser-0.5.3-py3.5.egg/robobrowser/forms/form.py", line 154, in prepare_fields
raise exceptions.InvalidSubmitError()
robobrowser.exceptions.InvalidSubmitError
I experienced the same issue today, with the same exact errors. One possible cause of the above issue is that your form2 actually contains more than one submit field, corresponding to more than one submit button in the original html. You can check this by print(len(list(form2.submit_fields.items(multi=True)))). If this is the case, your call to submit_form has to be modified as m.submit_form(form2, submit=your_submit), where the second argument your_submit is the relevant submit field you want to use. This reference discusses how to extract the submit field you desire.
Incidentally, if you wonder where the long print code comes from, it comes from the body of prepare_fields in robobrowser/forms/form.py, which is indicated in one of the error outputs you posted.
Hope this helps!
It happens when the package you installed courrupted in your current project...
So try to create a new project in pycharm. And install robobrowser library again....
And paste your file in new project...
Noteuse this method only if your code is completely correct 😉