本文主要是介绍【python 百度指数抓取】python 模拟登陆百度指数,图像识别百度指数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、算法思想
目的奔着去抓取百度指数的搜索指数,搜索指数的爬虫不像是其他爬虫,难度系数很高,分析之后发现是图片,坑爹的狠,想了下,由于之前做过身份证号码识别,验证码识别之类,豁然开朗,不就是图像识别麽,图像识别我不怕你,于是就有了思路,果然有异曲同工之妙,最后成功被我攻破了,大致思路如下:
1、首先得模拟登陆百度账号(用selenium+PhantomJS模拟登陆百度,获取cookie)
2、由于有该死的验证码,因此我们要绕过验证码,保存cookie模拟登陆(绕过万恶的验证码)
3、然后模拟登陆以后,程序截取屏幕保存到本地图片。(屏幕截屏)
4、读取本地图片。(读取图片)
5、找到搜索指数所在区域,裁剪图片。(裁剪图片)
6、下面就是进行图像识别,或者说验证码识别了。(去灰度化,二值化,图像识别)
二、截屏效果和识别效果
三、步骤详解
程序1:selenium 模拟登陆百度保存cookie到本地
#-*-coding:utf-8-*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from selenium import webdriver
import time
import pickle
driver=webdriver.PhantomJS(executable_path='D:\\Program Files\\Python27\\Scripts\\phantomjs.exe')driver.get('http://index.baidu.com/?tpl=trend&word=%D0%DB%B0%B2%D0%C2%C7%F8')
e1 = driver.find_element_by_id("TANGRAM_12__userName")
e1.send_keys("百度账号")
e2 = driver.find_element_by_id("TANGRAM_12__password")
e2.send_keys("百度密码")
e3 = driver.find_element_by_id("TANGRAM_12__submit")
e3.click()
cookies = driver.get_cookies()
time.sleep(6)pickle.dump(cookies, open("C:/cookies/cookies.pkl","wb"))
程序2:利用cookie模拟登陆百度,截屏,图像识别
#-*-coding:utf-8-*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from selenium import webdriver
import time
import pickle
driver=webdriver.PhantomJS(executable_path='D:\\Program Files\\Python27\\Scripts\\phantomjs.exe')
from PIL import Image
import pytesseract####################################第二步:利用cookie登录#####################################
driver.get("http://index.baidu.com")
cookies = pickle.load(open("C:/cookies/cookies.pkl", "rb"))
for cookie in cookies:driver.add_cookie(cookie)driver.get("http://index.baidu.com/?tpl=trend&word=%D0%DB%B0%B2%D0%C2%C7%F8")
time.sleep(3)driver.get_screenshot_as_file('E:/ID/5.png')
print("截屏结束.................")
driver.quit()
###########二值化算法
def binarizing(img,threshold):pixdata = img.load()w, h = img.sizefor y in range(h):for x in range(w):if pixdata[x, y] < threshold:pixdata[x, y] = 0else:pixdata[x, y] = 255return imgimg1=Image.open("E:/ID/5.png")
w,h=img1.size
# region = (220*3,320*3,420*3,380*3)//两个一起
##将图片放大3倍
out=img1.resize((w*3,h*3),Image.ANTIALIAS)
region1 = (220*3,320*3,320*3,380*3)
region2 = (320*3,320*3,420*3,380*3)
cropImg1 = out.crop(region1)
cropImg2 = out.crop(region2)
img1= cropImg1.convert('L')
img2= cropImg2.convert('L')
img1=binarizing(img1,200)
img2=binarizing(img2,200)
code1 = pytesseract.image_to_string(img1)
code2 = pytesseract.image_to_string(img2)print "整体搜索指数:" + str(code1).replace(".","").replace(" ",'')
print "移动搜索指数:" + str(code2).replace(".","").replace(" ",'')
# img1.show()
# img2.show()
这篇关于【python 百度指数抓取】python 模拟登陆百度指数,图像识别百度指数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!