Last active
September 5, 2018 15:00
-
-
Save seyna/bd793ed5bc7f42de85021ed712c36e6d to your computer and use it in GitHub Desktop.
Python codes to get API content and send POST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
# an example url, which actually returns JSON | |
url = "https://crawler.goodfind.com.tw/d/E0pvWZk1" | |
# this is how to do HTTP GET | |
r = requests.get(url) | |
# print returned content | |
print(r.text) | |
# if the returned content is in JSON format | |
j = json.loads(r.text) | |
# now 'j' object is in JSON format, you can retrieve data in hash way | |
len(j["items"]) # get size | |
j["items"][0] | |
# this is how to send a form POST with values and files | |
files = {'upload_file': open('README.md','rb')} | |
values = {'field_name_1': 'value_1', 'field_name_2': 'value_2'} | |
# change url to some address you want to send HTTP POST | |
url = "http://somesite.com/post_here" | |
r = requests.post(url, files=files, data=values) | |
# suppose we want to send data asynchronously | |
import grequests | |
urls = [ | |
'http://www.heroku.com', | |
'http://python-tablib.org', | |
'http://httpbin.org', | |
'http://python-requests.org', | |
'http://fakedomain/', | |
'http://kennethreitz.com' | |
] | |
rs = (grequests.post(url, files=files, data=values) for url in urls) | |
ret = grequests.map(rs) | |
print(ret) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment