利用selenium批量获取关键词百度指数
搞SEO的有时候会遇到批量查询百度指数的需求,但市面上大多数工具查询的数据有延时,并不是实时数据。那有没有更好的方式实时获取百度指数呢?
当然有。那就是利用selenium获取百度指数。得益于百度指数的改版,相对于以前获取百度指数的难度降低不少。改版之前如果想要获取百度指数的话,需要用selenium模拟浏览器,定位到百度指数数据的位置,然后把百度指数数据截图保存,然后利用图像识别技术最终识别出数据,难度比较高。总之一句话,改版后难度小,可以为所欲为。
运行代码之前,需要保证已安装selenium及pyquery库,示例代码如下:
代码示例
from pyquery import PyQuery as pqfrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECimport time,urllib,randomword_indexs = []options = webdriver.ChromeOptions()options.add_argument('--headless') #设置为无界面模式,不然会报错!!options.add_argument(r"--user-data-dir=C:\Users\hp\AppData\Local\Google\Chrome\User Data") #获取登陆后保持的cookiebrowser = 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_sourcedoc = pq(html)indexs = doc('.veui-table').text().split()# print(indexs)total_index = indexs[8]mobile_index = indexs[9]except:# print('{}无指数'.format(kw))total_index = 0mobile_index = 0index = '{}\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
阅读剩余
THE END