0

API Google 검색 콘솔 데이터를 통해 Python (2.7) 스크립트를 다운로드하고 있습니다. 후자의 경우Python 스크립트를 통해 Google Search Console에서 더 많은 속성 쿼리하기

>python script. py ´http://www.example.com´ ´01-01-2000´ ´01-02-2000´ 

나는 그것이 timedelta를 가져, 그 인수를 참조 라인을 주석 처리 할 수있는 관리 :

argparser = argparse.ArgumentParser(add_help=False) 
argparser.add_argument('property_uri', type=str, 
         help=('Site or app URI to query data for (including ' 
         'trailing slash).')) 
# Start and end dates are commented out as timeframe is dynamically set 
'''argparser.add_argument('start_date', type=str, 
         help=('Start date of the requested date range in ' 
         'YYYY-MM-DD format.')) 
argparser.add_argument('end_date', type=str, 
         help=('End date of the requested date range in ' 
         'YYYY-MM-DD format.'))''' 

now = datetime.datetime.now() 
StartDate = datetime.datetime.now()- timedelta(days=14) 
EndDate = datetime.datetime.now()- timedelta(days=7) 

From = StartDate.strftime('%Y-%m-%d') 

To = EndDate.strftime('%Y-%m-%d') 

request = { 
     'startDate': StartDate.strftime('%Y-%m-%d'), 
     'endDate': EndDate.strftime('%Y-%m-%d'), 
     'dimensions': ['query'], 
을 스크립트를 실행할 때 나는 재산을 없애 좋아하고 인수를 날짜 것

이제 속성 인수를 없애고 간단하게 스크립트를 시작하고 스크립트 자체에 지정된 속성을 가질 수 있습니다. 마지막 목표는 하나의 스크립트 만 사용하여 여러 속성에서 데이터를 가져 오는 것입니다.

날짜는 같지만 운이없는 동일한 절차를 반복하려했습니다. 말할 필요도없이 나는 코딩 초보자이다.

답변

0

지도로 Google에서 제공 한 샘플 스크립트에서 작업 할 때 동일한 문제가 있었기 때문에 도움이 될 것이라고 생각합니다. 나는 당신이 당신의 코드를 얻은 것 같아요?

문제는 스크립트가 googleapiclient 라이브러리에서 sample_tools.py 스크립트를 사용한다는 것입니다.이 스크립트는 모든 인증 비트를 추상화하여 빠른 쿼리를 쉽게 만들 수 있습니다. 코드를 수정하려면 처음부터 코드를 작성하는 것이 좋습니다.

다음은 필자가 유용하다고 생각할 수있는 다양한 문서들로부터 함께 다룬 필자의 기능들입니다.

1 단계 : 인증

def authenticate_http(): 
    """Executes a searchAnalytics.query request. 

    Args: 
    service: The webmasters service to use when executing the query. 
    property_uri: The site or app URI to request data for. 
    request: The request to be executed. 

    Returns: 
    An array of response rows. 
    """ 
    # create flow object 
    flow = flow_from_clientsecrets('path to client_secrets.json', 
     scope='https://www.googleapis.com/auth/webmasters.readonly', 
     redirect_uri='urn:ietf:wg:oauth:2.0:oob') 

    storage = Storage('credentials_file') 
    credentials = storage.get() 
    if credentials: 
     # print "have auth code" 
     http_auth = credentials.authorize(Http()) 
    else: 
     print "need auth code" 
     # get authorization server uri 
     auth_uri = flow.step1_get_authorize_url() 
     print auth_uri 

     # get credentials object 
     code_input = raw_input("Code: ") 
     credentials = flow.step2_exchange(code_input) 
     storage.put(credentials) 

     # apply credential headers to all requests 
     http_auth = credentials.authorize(Http()) 

    return http_auth 

2 단계 : 빌드 서비스 개체

def build_service(api_name, version): 
    # use authenticate_http to return the http object 
    http_auth = authenticate_http() 

    # build gsc service object 
    service = build(api_name, version, http=http_auth) 
    return service 

3 단계 : 실행 요청

def execute_request(service, property_uri, request): 
    """Executes a searchAnalytics.query request. 
    Args: 
    service: The webmasters service to use when executing the query. 
    property_uri: The site or app URI to request data for. 
    request: The request to be executed. 
    Returns: 
    An array of response rows. 
    """ 
    return service.searchanalytics().query(
     siteUrl=property_uri, body=request).execute() 

4 단계 : 홈페이지()

여러 속성에 대해 6,

방금 ​​속성 세트의 목록을 만들 수 있습니다 설정, 다음 루프를 만들고 'execute_request'기능

이 도움이 희망의 'URL'인수로 설정 한 각 속성을 전달합니다!

관련 문제