개발-IT/python

python 삽질 노트

바다로그 2020. 8. 26. 16:56

html에서 이미지 뽑기,  for 문에서 인텍스 값 사용하기 

html="""listed under the menu button\u00a0<img alt=\"k" 
src="https://eu26.content.force.com/servlet/rtaImage?eid=ka4.png\">
</img>"""

image_list=[]
image_src=dict()

soup = BeautifulSoup(html,features="html.parser")

for link in soup.find_all('img'):        #html에서 img만 뽑아 image_list 저장
    image_list.append(link)              #list에 추가
print("image_list",image_list) 


for idx, image in enumerate(image_list):  #for 문의 idx 인덱스 카운터
    image_src[idx]=image['src']           #idx을 키값으로 사용 딕션어로형태로 저장. 
print( "image_src->",image_src )
 
 
 결과값
image_list [<img alt="k" src="https://eu26.content.force.com/servlet/rtaImage?eid=ka4.png"/>]
image_src-> {0: 'https://eu26.content.force.com/servlet/rtaImage?eid=ka4.png'}

 

파일저장. 

def download_attachement(url,fileName):
  api_response = requests.get(url, headers = { 'Content-Type': 'application/text', 'Authorization': 'Bearer ' + access_token })
  file = open(fileName, "wb")
  file.write(api_response.content)
  file.close()
  print('output file: '  + os.path.realpath(file.name))
  api_response.close()

 

salesforce soql 쿼리 날리기 . 

import requests
import json 
import os
params = {
    "grant_type": "password",
    "client_id": "Consumer Key", # Consumer Key
    "client_secret":"ConsumerSecret", # Consumer Secret
    "username": "username", # The email you use to login
    "password": "password" # Concat your password and your security token
}
r = requests.post("https://login.salesforce.com/services/oauth2/token", params=params)
# if you connect to a Sandbox, use test.salesforce.com instead
access_token = r.json().get("access_token")
instance_url = r.json().get("instance_url")
sf_login_id=r.json().get("id")
token_type=r.json().get("token_type")
issued_at=r.json().get("issued_at")
signature=r.json().get("signature")
 
print(r.json()) 

def sf_api_call(action, parameters = {}, method = 'get', data = {}):
    """
    Helper function to make calls to Salesforce REST API.
    Parameters: action (the URL), URL params, method (get, post or patch), data for POST/PATCH.
    """
    headers = {
        'Content-type': 'application/json',
        'Accept-Encoding': 'gzip',
        'Authorization': 'Bearer %s' % access_token
    }
    if method == 'get':
        r = requests.request(method, instance_url+action, headers=headers, params=parameters, timeout=30)
    elif method in ['post', 'patch']:
        r = requests.request(method, instance_url+action, headers=headers, json=data, params=parameters, timeout=10)
    else:
        # other methods not implemented in this example
        raise ValueError('Method should be get or post or patch.')
    print('Debug: API %s call: %s' % (method, r.url) )
    if r.status_code < 300:
        if method=='patch':
            return None
        else:
            return r.json()
    else:
        raise Exception('API error when calling %s : %s' % (r.url, r.content))

articles=json.dumps(sf_api_call('/services/data/v39.0/query/', 
                     {
                        'q': """SELECT MasterVersionId,
                                    ArticleNumber,
                                    Title,
                                    Answer__c,
                                    File_Attachment__Name__s,
                                    File_Attachment__Body__s,
                                    File_Attachment__ContentType__s,
                                    File_Attachment__Length__s,
                                    LastPublishedDate 
                                FROM  FAQ_Subscribers__kav  
                                WHERE PublishStatus='online'
                                AND language ='en_US'
                                AND IsVisibleInApp =true
                                """}),
                    indent=2)

 

Object 내용보기 

def print_obj_data(obj_name): 
  for attr in dir(obj_name):
    print("obj_name.%s = %r" % (attr, getattr(obj_name, attr)))

JSON

stackoverflow.com/questions/5508509/how-do-i-check-if-a-string-is-valid-json-in-python

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

import json

def is_json(myjson):
  try:
    json_object = json.loads(myjson)
  except ValueError as e:
    return False
  return True

 

pip install prettyprinter

from datetime import datetime
from prettyprinter import pprint
pprint({'beautiful output': datetime.now()})