百度图片动态爬取3.0

来源:互联网 发布:拉爆淘宝首页流量 编辑:程序博客网 时间:2024/06/04 18:57

之前我写过百度图片的1.0,2.0版本,代码在我的GitHub,以及简书上。在这里我就不对1.0,2.0版本的细节做过多的描述:
1.0:是基础版本:主要实现了图片的提取与下载
2.0:是对1.0的提升,主要有两方面的内容:
1. 代码函数化
2. 数据存储方式的变化

GitHub地址:https://github.com/RHobart/Web-Crawlers
简书地址:http://www.jianshu.com/p/567542a57af2

今天我在这里写的是关于3.0,这个3.0是对之前百度图片动态爬取的一优化;主要涉及异常处理,跟2.0版本的主要内容相差不大,代码如下:

#encoding="utf-8"__author__='Hobart'from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom bs4 import BeautifulSoup as bsimport urllib.requestimport pymysqlimport reimport osimport time #启动谷歌浏览器驱动def start_brower(url):    driver=webdriver.Chrome()    driver.get(url)    time.sleep(5)    return driver#动态获取图片信息def get_img_information(location,last_location,count,driver):    #当鼠标的位置小于最后的鼠标位置时,循环执行    while location<last_location:        #获取页面源码        html_page=driver.page_source        #利用Beautifulsoup4创建soup对象并进行页面解析        soup=bs(html_page,"html.parser")        time.sleep(2)        #通过soup对象中的findAll函数图像信息提取        imgs=soup.findAll('img',{'src':re.compile(r'https:.*\.(jpg|png)')})        time.sleep(2)        #将图片信息存储到Mysql数据库中        for img in imgs:            print(str(count)+':'+img.get('src')+'\n')            name=str(count)            style=img.get('src')[-3:]            data=img.get('src')            cursor.execute("insert into img (img_name,img_stype,img_data) values(%s,%s,%s)",(name,style,data))            conn.commit()            count+=1        time.sleep(2)        #通过Selenium模拟鼠标滚动        js="$(document).scrollTop(%d)"%location          driver.execute_script(js)         location+=500        time.sleep(3)        imgs=[]url="https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%85%AB%E5%8D%A6%E5%9B%BE&oq=bagua&rsp=0"#启动浏览器,打开网站driver=start_brower(url)#mysql数据库连接方式conn=pymysql.connect(host='localhost',port=3306,user='admin',password='admin',db='img')try:        if conn:        print("数据库连接成功")        cursor=conn.cursor()        get_img_information(0,3000,1,driver)        cursor.close()        conn.close()    else:        print("数据库连接失败")finally:    #退出浏览器    driver.quit()

其主要思路如下:

第一步:使用selenium打开谷歌浏览器驱动

第二步:打开要访问的网站

第三不:将selenium打开的网站源码赋给一个对象

第四步:利用Beautifulsoup4创建soup对象,并解析页面,得到页面数据

第五步:利用soup对象中的findAll函数提取相应的图片数据

第六步:将图片数据写入相应的盘中

第七步:通过selenium模拟鼠标向下滚动,回到第三步,循环执行,直到滚动到所设定的鼠标位置然后退出。

最后一步退出浏览器

是不是很简单的,另外4.0版本正在写,代码数量也会相应的增加,不过功能也更加强大,不仅仅只是输入url提取图片数据,还有其他方式,之后我会将4.0版本代码放到CSDN博客上来。

原创粉丝点击