利用selenium批量获取关键词百度指数

搞SEO的有时候会遇到批量查询百度指数的需求,但市面上大多数工具查询的数据有延时,并不是实时数据。那有没有更好的方式实时获取百度指数呢?

当然有。那就是利用selenium获取百度指数。得益于百度指数的改版,相对于以前获取百度指数的难度降低不少。改版之前如果想要获取百度指数的话,需要用selenium模拟浏览器,定位到百度指数数据的位置,然后把百度指数数据截图保存,然后利用图像识别技术最终识别出数据,难度比较高。总之一句话,改版后难度小,可以为所欲为。

运行代码之前,需要保证已安装selenium及pyquery库,示例代码如下:

代码示例

from pyquery import PyQuery as pq
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time,urllib,random

word_indexs = []
options = webdriver.ChromeOptions()
options.add_argument('--headless')  #设置为无界面模式,不然会报错!!
options.add_argument(r"--user-data-dir=C:\Users\hp\AppData\Local\Google\Chrome\User Data")  #获取登陆后保持的cookie
browser = webdriver.Chrome(chrome_options = options)
wait = WebDriverWait(browser,5)
for kw in open('keywords.txt',encoding='utf-8-sig'):
    kw = kw.rstrip()
    word = urllib.parse.quote(kw)
    newurl = 'http://index.baidu.com/v2/main/index.html#/trend/{}?words={}'.format(word,word)
    browser.get(newurl)
    time.sleep(random.uniform(0.5, 1.5))
    try:
        wait.until(EC.visibility_of_element_located((By.TAG_NAME,'tbody')))  #等到元素可见
        html = browser.page_source
        doc = pq(html)
        indexs = doc('.veui-table').text().split()
        # print(indexs)
        total_index = indexs[8]
        mobile_index = indexs[9]
    except:
        # print('{}无指数'.format(kw))
        total_index = 0
        mobile_index = 0
    index = '{}\t{}\t{}'.format(kw,total_index,mobile_index)
    word_indexs.append(index+'\n')
    print(index)
with open('百度指数查询结果.txt','w',encoding='utf-8') as f:
    f.writelines(word_indexs)

参数说明

--user-data-dir:修改成电脑Chrome浏览器User Data文件夹所在路径

keywords.txt:关键词存放文件,一行一个

什么?你还想知道百度指数改版前的获取方法?我也不会,不过有代码参考,一并奉上。见:https://github.com/plus0318/BaiduIndex

PS:经测试查询500-600个关键词的时候,百度指数会封账号,但不会封IP换账号可以继续采集。被封账号第二天可自动解封。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。