加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-3.x – 谷歌Adwords流量估算服务和Python

发布时间:2020-12-20 13:15:35 所属栏目:Python 来源:网络整理
导读:我已下载了一个代码示例,该示例查找特定关键字并提取一些指标.我注意到很多Google Adwords API示例都符合 python 3.x,所以我想知道是否存在问题?请参阅下面的代码示例: from googleads import adwordsdef main(client): # Initialize appropriate service.
我已下载了一个代码示例,该示例查找特定关键字并提取一些指标.我注意到很多Google Adwords API示例都符合 python 3.x,所以我想知道是否存在问题?请参阅下面的代码示例:

from googleads import adwords


def main(client):
  # Initialize appropriate service.
  traffic_estimator_service = client.GetService(
      'TrafficEstimatorService',version='v201609')

  # Construct selector object and retrieve traffic estimates.
  keywords = [
      {'text': 'mars cruise','matchType': 'BROAD'},{'text': 'cheap cruise','matchType': 'PHRASE'},{'text': 'cruise','matchType': 'EXACT'}
  ]
  negative_keywords = [
      {'text': 'moon walk','matchType': 'BROAD'}
  ]
  keyword_estimate_requests = []
  for keyword in keywords:
    keyword_estimate_requests.append({
        'keyword': {
            'xsi_type': 'Keyword','matchType': keyword['matchType'],'text': keyword['text']
        }
    })

  for keyword in negative_keywords:
    keyword_estimate_requests.append({
        'keyword': {
            'xsi_type': 'Keyword','text': keyword['text']
        },'isNegative': 'true'
    })

  # Create ad group estimate requests.
  adgroup_estimate_requests = [{
      'keywordEstimateRequests': keyword_estimate_requests,'maxCpc': {
          'xsi_type': 'Money','microAmount': '1000000'
      }
  }]

  # Create campaign estimate requests.
  campaign_estimate_requests = [{
      'adGroupEstimateRequests': adgroup_estimate_requests,'criteria': [
          {
              'xsi_type': 'Location','id': '2840'  # United States.
          },{
              'xsi_type': 'Language','id': '1000'  # English.
          }
      ],}]

  # Create the selector.
  selector = {
      'campaignEstimateRequests': campaign_estimate_requests,}

  # Optional: Request a list of campaign-level estimates segmented by
  # platform.
  selector['platformEstimateRequested'] = True

  # Get traffic estimates.
  estimates = traffic_estimator_service.get(selector)

  campaign_estimate = estimates['campaignEstimates'][0]

  # Display the campaign level estimates segmented by platform.
  if 'platformEstimates' in campaign_estimate:
    platform_template = ('Results for the platform with ID: "%d" and name: '
                         '"%s".')
    for platform_estimate in campaign_estimate['platformEstimates']:
      platform = platform_estimate['platform']
      DisplayEstimate(platform_template % (platform['id'],platform['platformName']),platform_estimate['minEstimate'],platform_estimate['maxEstimate'])

  # Display the keyword estimates.
  if 'adGroupEstimates' in campaign_estimate:
    ad_group_estimate = campaign_estimate['adGroupEstimates'][0]
    if 'keywordEstimates' in ad_group_estimate:
      keyword_estimates = ad_group_estimate['keywordEstimates']
      keyword_template = ('Results for the keyword with text "%s" and match '
                          'type "%s":')

      keyword_estimates_and_requests = zip(keyword_estimates,keyword_estimate_requests)

      for keyword_tuple in keyword_estimates_and_requests:
        if keyword_tuple[1].get('isNegative',False):
          continue
        keyword = keyword_tuple[1]['keyword']
        keyword_estimate = keyword_tuple[0]
        DisplayEstimate(keyword_template % (keyword['text'],keyword['matchType']),keyword_estimate['min'],keyword_estimate['max'])


def _CalculateMean(min_est,max_est):
  if min_est and max_est:
    return (float(min_est) + float(max_est)) / 2.0
  else:
    return None


def _FormatMean(mean):
  if mean:
    return '%.2f' % mean
  else:
    return 'N/A'


def DisplayEstimate(message,min_estimate,max_estimate):
  """Displays mean average cpc,position,clicks,and total cost for estimate.
  Args:
    message: str message to display for the given estimate.
    min_estimate: sudsobject containing a minimum estimate from the
      TrafficEstimatorService response.
    max_estimate: sudsobject containing a maximum estimate from the
      TrafficEstimatorService response.
  """
  # Find the mean of the min and max values.
  mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'],max_estimate['averageCpc']['microAmount'])
                  if 'averageCpc' in min_estimate else None)
  mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'],max_estimate['averagePosition'])
                  if 'averagePosition' in min_estimate else None)
  mean_clicks = _CalculateMean(min_estimate['clicksPerDay'],max_estimate['clicksPerDay'])
  mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'],max_estimate['totalCost']['microAmount'])

  print (message)
  print ('Estimated average CPC: %s' % _FormatMean(mean_avg_cpc))
  print ('Estimated ad position: %s' % _FormatMean(mean_avg_pos))
  print ('Estimated daily clicks: %s' % _FormatMean(mean_clicks))
  print ('Estimated daily cost: %s' % _FormatMean(mean_total_cost))


if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()

  main(adwords_client)

这是错误消息:

(Money) not-found
path: "Money",not-found
(Keyword) not-found
path: "Keyword",not-found
(Location) not-found
path: "Location",not-found
(Language) not-found
path: "Language",not-found
<suds.sax.document.Document object at 0x03BF1D10>
Server raised fault in response.
Traceback (most recent call last):
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagessudstransporthttp.py",line 82,in send
    fp = self.u2open(u2request)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagessudstransporthttp.py",line 132,in u2open
    return url.open(u2request,timeout=tm)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32liburllibrequest.py",line 472,in open
    response = meth(req,response)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32liburllibrequest.py",line 582,in http_response
    'http',request,response,code,msg,hdrs)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32liburllibrequest.py",line 510,in error
    return self._call_chain(*args)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32liburllibrequest.py",line 444,in _call_chain
    result = func(*args)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32liburllibrequest.py",line 590,in http_error_default
    raise HTTPError(req.full_url,hdrs,fp)
urllib.error.HTTPError: HTTP Error 500: Internal Server Error

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagessudsclient.py",line 613,in send
    reply = self.options.transport.send(request)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagessudstransporthttp.py",line 94,in send
    raise TransportError(e.msg,e.code,e.fp)
suds.transport.TransportError: Internal Server Error

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32adwords test - Copy (2).py",line 177,in <module>
    main(adwords_client)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32adwords test - Copy (2).py",line 95,in main
    estimates = traffic_estimator_service.get(selector)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagesgoogleadscommon.py",line 696,in MakeSoapRequest
    raise e
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagesgoogleadscommon.py",line 692,in MakeSoapRequest
    for arg in args])
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagessudsclient.py",line 521,in __call__
    return client.invoke(args,kwargs)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagessudsclient.py",line 581,in invoke
    result = self.send(soapenv)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagessudsclient.py",line 619,in send
    description=tostr(e),original_soapenv=original_soapenv)
  File "C:UserssfroeseAppDataLocalProgramsPythonPython35-32libsite-packagessudsclient.py",line 670,in process_reply
    raise WebFault(fault,replyroot)
suds.WebFault: Server raised fault: '[AuthenticationError.CLIENT_CUSTOMER_ID_IS_REQUIRED @ ; trigger:'<null>']'

解决方法

您应该在googleads.yaml文件中设置client_customer_id.您可以从您的经理帐户获取client_customer_id.转到您的经理帐户并添加客户端,然后从屏幕的右上角复制您的ID.在googleads.yaml文件中将该ID粘贴到client_customer_id.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读