百度指数抓取,再用图像识别得到指数
前言:
土福曾说,百度指数很难抓,在淘宝上面是20块1个关键字:
哥那么叼的人怎么会被他吓到,于是乎花了零零碎碎加起来大约2天半搞定,在此鄙视一下土福
安装的库很多:
谷歌图像识别tesseract-ocrpip3 install pillowpip3 install pyocrselenium2.45Chrome47.0.2526.106 m or Firebox32.0.1chromedriver.exe
图像识别验证码请参考:https://mon.action_chains import ActionChainsActionChains(browser).move_to_element_with_offset(xoyelement,x_0,y_0).perform()
但是这样子确定的点指出是在这个位置:
也就是矩形的左上角,这里是不会加载js显示弹出框的,所以要给横坐标+1:
x_0 = 1y_0 = 0
写个按照天数的循环,让横坐标累加:
# 按照选择的天数循环for i in range(day): # 构造规则 if day == 7: x_0 = x_0 + 202.33 elif day == 30: x_0 = x_0 + 41.68 elif day == 90: x_0 = x_0 + 13.64 elif day == 180: x_0 = x_0 + 6.78
鼠标横移时会弹出框,在网址里面找到这个框:
selenium自动识别之...:
# <div class="imgtxt" style="margin-left:-117px;"></div>imgelement = browser.find_element_by_xpath('//div[@id="viewbox"]')
并且确定这个框的大小位置:
# 找到图片坐标locations = imgelement.locationprint(locations)# 找到图片大小sizes = imgelement.sizeprint(sizes)# 构造指数的位置rangle = (int(locations['x']), int(locations['y']), int(locations['x'] + sizes['width']), int(locations['y'] + sizes['height']))
截取的图形为:
下面的思路就是:
1.将整个屏幕截图下来
2.打开截图用上面得到的这个坐标rangle进行裁剪
但是最后裁剪出来的是上面的那个黑框,我想要的效果是:
所以要对rangle进行计算,但是我懒,忽略了搜索词的长度,直接暴力的写成:
# 构造指数的位置rangle = (int(locations['x'] + sizes['width']/3), int(locations['y'] + sizes['height']/2), int(locations['x'] + sizes['width']*2/3), int(locations['y'] + sizes['height']))
这个写法最终不太好,最起码要对keyword的长度进行判断,长度过长会导致截图坐标出现偏差,反正我知道怎么做,就是不写出来给你们看!
后面的完整代码是:
# <div class="imgtxt" style="margin-left:-117px;"></div>imgelement = browser.find_element_by_xpath('//div[@id="viewbox"]')# 找到图片坐标locations = imgelement.locationprint(locations)# 找到图片大小sizes = imgelement.sizeprint(sizes)# 构造指数的位置rangle = (int(locations['x'] + sizes['width']/3), int(locations['y'] + sizes['height']/2), int(locations['x'] + sizes['width']*2/3), int(locations['y'] + sizes['height']))# 截取当前浏览器path = "../baidu/" + str(num)browser.save_screenshot(str(path) + ".png")# 打开截图切割img = Image.open(str(path) + ".png")jpg = img.crop(rangle)jpg.save(str(path) + ".jpg")
但是后面发现裁剪的图片太小,识别精度太低,所以需要对图片进行扩大:
# 将图片放大一倍# 原图大小73.29jpgzoom = Image.open(str(path) + ".jpg")(x, y) = jpgzoom.sizex_s = 146y_s = 58out = jpgzoom.resize((x_s, y_s), Image.ANTIALIAS)out.save(path + 'zoom.jpg', 'png', quality=95)
原图大小请 右键->属性->详细信息 查看,我的是长73像素,宽29像素
最后就是图像识别
# 图像识别index = []image = Image.open(str(path) + "zoom.jpg")code = pytesseract.image_to_string(image)if code: index.append(code)
最后效果图:
源码下载:demo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。