百度API扩展关键词提取代码

风景
使用百度API V4接口,V3接口已经不能用了。但V4接口不太稳定,经常出现跑着跑着返回数据为空的情况,但重新执行又可以出结果,不知道为啥。

# coding:utf-8
# 接口PDF:https://dev2.baidu.com/sms_zh/uploads/en/2016/2/V4cn2016-01-22_.1-24194523.pdf
 
from sms_service_KRService import *
import requests,json,csv,sys,os,time
 
reload(sys)
sys.setdefaultencoding('utf-8')
 
outcsvfile = open('outfile.csv','ab')
 
service = sms_service_KRService()
service.setUsername("{username}")
service.setPassword("{password}")
service.setToken("{token}")
 
for query in open(sys.argv[1]):
    query = query.strip()
 
    request = {
        'query':'%s' % query,
        'seedFilter': {
                        'device':0,       # 设备类型。0:pc+无线,1:pc,2:无线
                        'maxNum':300,     # 返回的最大结果数,默认300。取值范围:1-1000,按相关性排序
                        #'competeLow':0,  #返回竞争度大于competeLow的词,取值范围0-99
                        'pvLow':0,        #返回日均搜索量大于pvLow的词
                        #'regionExtend':false   #返回词是否包含地域扩展词,默认为false
                        },
        'queryType':1,
        }
 
    # print '===========>> %s' % query
 
    res = service.getKRByQuery(request)
 
    try:
        for line in res['body']['data']:
            pv = line[u'pv']            # 近30天内日均搜索次数(pc + mobile)
            #recBid = line[u'recBid']   # 左侧准入价
            #pcPV = line[u'pcPV']       # 近30天内PC端日均搜索次数
            #wordPackage = line[u'wordPackage'] # 关键词所属包名
            #showReasons = line[u'showReasons'] # 展现理由
            #competition = line[u'competition'] # 竞争激烈度
            #mobilePV = line[u'mobilePV']       # 近30天内无线端日均搜索次数
            #businessPoints = line[u'businessPoints']   # 所属业务点名
            word = line[u'word']        # 返回推荐字面
 
            data = []
            data.append(word)
            data.append(pv)
            data.append(query)
            writer = csv.writer(outcsvfile,dialect='excel')
            writer.writerow(data)
        time.sleep(5)
    except:
        print '--------------》请求频率太高,稍等片刻《-------------'
        time.sleep(60)
        continue

GOGO闯微信公众号:流量贩子

3 thoughts on “百度API扩展关键词提取代码”

Leave a Comment