爬虫学习1-selenium简单爬虫
Ebounce
撰写于 2019年 05月 03 日

最近都没怎么写博客了,一是前段时间有点忙,二是研究了一段时间的爬虫,废话不多说直接上代码吧。
以下代码主要参照一个python爬虫学习的公众号--学习python的正确姿势,是非常有趣的python学习公众号,你看了下面的代码用途就知道为什么有趣了。
<!--more-->

from selenium import webdriver
from selenium.webdriver.common.by import By//通过什么方式去定位元素的一个类
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.firefox.options import Options//可以从这个去设置浏览器为无头模式
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait//引入一个控制是否超时的机制
from bs4 import BeautifulSoup//解析xml的库
import time
import xlwt
import json
"""这里主要是引入一些定制好的库,比如最出名的selenium是可以模拟浏览器的操作;然后time库是用于进行一定时间的休息,算是反反爬虫,xlwt是一个写入excel文件的库
json就不用我多说了吧。
"""
def search():
    try:
        print("开始访问B站..............")
        fox.get(url)
//这里的url是B站的首页
        index=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#primary_menu>ul>li.home>a")))
        index.click()
//这里我们通过css选择器定位到了B站的”首页“元素,由于刚打开开始爬取是会要求我们登陆,从而影响定位,所以先点击首页刷新一下
        input=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#banner_link>div>div>form>input")))
        input.send_keys("鸡你太美")
//这里我们选中了B站的搜索框,并输入了关键字”鸡你太美“
        button=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#banner_link>div>div>form>button")))
        button.click()
//这里选中了B站的搜索按钮,并点击了搜索
        print("跳转新窗口")
        all_h = fox.window_handles
        fox.switch_to.window(all_h[1])
        get_source()
        total=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#server-search-app>div.contain>div.body-contain>div>div.page-wrap>div>ul>li.page-item.last>button")))
        //这里定位到了B站的最后一页元素
        return int(total.text)
//获得最后一页元素的数字,方便我们知道要执行多少次
    except TimeoutException:
        return search()

def next_page(page_num):
    try:
        print('获取下一页数据')
        time.sleep(3)
//爬取太快似乎会被B站搞,所以暂时性的休眠3秒,如果决定慢也可以自行修改
        next= wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#server-search-app>div.contain>div.body-contain >div>div.page-wrap>div>ul>li.page-item.next>button')))
        next.click()//定位到了下一个元素并点击
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#server-search-app>div.contain>div.body-contain>div>div.page-wrap>div>ul>li.page-item.active>button'),str(page_num)))//这里定位到当前页面
        get_source()
    except TimeoutException:
        fox.refresh()
        return next_page(page_num)


def get_source():
    try:
        print("正在获得当前数据中.......")
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#server-search-app>div.contain>div.body-contain>div>div.result-wrap.clearfix")))
        html=fox.page_source//这里是获得B站下面一大块具有视频信息的DOM位置
        soup=BeautifulSoup(html,'lxml')
        print("获得数据完毕.......")
        save_data(soup)
    except:
        pass

def save_data(soup):
    print("开始写入数据...........")
    list=soup.find(class_="all-contain").find_all(class_="info")
    for item in list:
        item_title=item.find("a").get("title")//得到标题
        item_link=item.find("a").get("href")//得到链接
        item_dec=item.find(class_="des hide").text//得到描述
        item_view=item.find(class_="so-icon watch-num").text//得到播放量
        item_time=item.find(class_="so-icon time").text//得到上传时间
        item_up=item.find(class_="up-name").text//得到UP主名称
        print(item_up)//这里将其打印出来,以便在控制台观察是否出错
        item_danmu=item.find(class_="so-icon hide").text//这里是弹幕数
        print("爬取:"+item_title)
        global n//设置为全局变量
        sheet.write(n, 0,item_title)
        sheet.write(n, 1,item_link)
        sheet.write(n, 2, item_dec)
        sheet.write(n, 3, item_view)
        sheet.write(n, 4, item_time)
        sheet.write(n, 5, item_up)
        sheet.write(n, 6, item_danmu)//分别写入xls对应得列
        print("当前数据写入完成........")
        n=n+1
data=xlwt.Workbook(encoding="utf-8",style_compression=0)
sheet=data.add_sheet("鸡你太美",cell_overwrite_ok=True)
sheet.write(0,0,"名称")
sheet.write(0,1,"链接")
sheet.write(0,2,"描述")
sheet.write(0,3,"观看次数")
sheet.write(0,4,"上传时间")
sheet.write(0,5,"Up主")
sheet.write(0,6,"弹幕数")
n=1//进行excel最初列的设置
url = "https://www.bilibili.com"
fox = webdriver.Firefox()
//安装什么浏览器的内核就用什么浏览器
wait = WebDriverWait(fox,10)
//设置最大的等待时间是多少
try:
    total = search()
    print(total)
    for i in range(1, int(total)+1)://
这里用获得的最大页数控制循环次数,因为前面以及爬取了第一页因此从1开始
        next_page(i)
finally:
    fox.close()
data.save(u"菜虚鲲打篮球.xls")

效果图如下:
刚开始的时候弹出了登录框:

随后进行刷新:

然后开始爬取:


最后爬取的文件和内容:


PS:这里选中元素也可以使用XML,但是无论CSS选择器还是XML都能在定位好元素后,对定位元素点右键复制,能够
直接复制CSS选择器和XML不需要自行填写

爬虫学习1-selenium简单爬虫

最近都没怎么写博客了,一是前段时间有点忙,二是研究了一段时间的爬虫,废话不多说直接上代码吧。
以下代码主要参照一个python爬虫学习的公众号--学习python的正确姿势,是非常有趣的python学习公众号,你看了下面的代码用途就知道为什么有趣了。
<!--more-->

from selenium import webdriver
from selenium.webdriver.common.by import By//通过什么方式去定位元素的一个类
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.firefox.options import Options//可以从这个去设置浏览器为无头模式
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait//引入一个控制是否超时的机制
from bs4 import BeautifulSoup//解析xml的库
import time
import xlwt
import json
"""这里主要是引入一些定制好的库,比如最出名的selenium是可以模拟浏览器的操作;然后time库是用于进行一定时间的休息,算是反反爬虫,xlwt是一个写入excel文件的库
json就不用我多说了吧。
"""
def search():
    try:
        print("开始访问B站..............")
        fox.get(url)
//这里的url是B站的首页
        index=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#primary_menu>ul>li.home>a")))
        index.click()
//这里我们通过css选择器定位到了B站的”首页“元素,由于刚打开开始爬取是会要求我们登陆,从而影响定位,所以先点击首页刷新一下
        input=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#banner_link>div>div>form>input")))
        input.send_keys("鸡你太美")
//这里我们选中了B站的搜索框,并输入了关键字”鸡你太美“
        button=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#banner_link>div>div>form>button")))
        button.click()
//这里选中了B站的搜索按钮,并点击了搜索
        print("跳转新窗口")
        all_h = fox.window_handles
        fox.switch_to.window(all_h[1])
        get_source()
        total=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#server-search-app>div.contain>div.body-contain>div>div.page-wrap>div>ul>li.page-item.last>button")))
        //这里定位到了B站的最后一页元素
        return int(total.text)
//获得最后一页元素的数字,方便我们知道要执行多少次
    except TimeoutException:
        return search()

def next_page(page_num):
    try:
        print('获取下一页数据')
        time.sleep(3)
//爬取太快似乎会被B站搞,所以暂时性的休眠3秒,如果决定慢也可以自行修改
        next= wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#server-search-app>div.contain>div.body-contain >div>div.page-wrap>div>ul>li.page-item.next>button')))
        next.click()//定位到了下一个元素并点击
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#server-search-app>div.contain>div.body-contain>div>div.page-wrap>div>ul>li.page-item.active>button'),str(page_num)))//这里定位到当前页面
        get_source()
    except TimeoutException:
        fox.refresh()
        return next_page(page_num)


def get_source():
    try:
        print("正在获得当前数据中.......")
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#server-search-app>div.contain>div.body-contain>div>div.result-wrap.clearfix")))
        html=fox.page_source//这里是获得B站下面一大块具有视频信息的DOM位置
        soup=BeautifulSoup(html,'lxml')
        print("获得数据完毕.......")
        save_data(soup)
    except:
        pass

def save_data(soup):
    print("开始写入数据...........")
    list=soup.find(class_="all-contain").find_all(class_="info")
    for item in list:
        item_title=item.find("a").get("title")//得到标题
        item_link=item.find("a").get("href")//得到链接
        item_dec=item.find(class_="des hide").text//得到描述
        item_view=item.find(class_="so-icon watch-num").text//得到播放量
        item_time=item.find(class_="so-icon time").text//得到上传时间
        item_up=item.find(class_="up-name").text//得到UP主名称
        print(item_up)//这里将其打印出来,以便在控制台观察是否出错
        item_danmu=item.find(class_="so-icon hide").text//这里是弹幕数
        print("爬取:"+item_title)
        global n//设置为全局变量
        sheet.write(n, 0,item_title)
        sheet.write(n, 1,item_link)
        sheet.write(n, 2, item_dec)
        sheet.write(n, 3, item_view)
        sheet.write(n, 4, item_time)
        sheet.write(n, 5, item_up)
        sheet.write(n, 6, item_danmu)//分别写入xls对应得列
        print("当前数据写入完成........")
        n=n+1
data=xlwt.Workbook(encoding="utf-8",style_compression=0)
sheet=data.add_sheet("鸡你太美",cell_overwrite_ok=True)
sheet.write(0,0,"名称")
sheet.write(0,1,"链接")
sheet.write(0,2,"描述")
sheet.write(0,3,"观看次数")
sheet.write(0,4,"上传时间")
sheet.write(0,5,"Up主")
sheet.write(0,6,"弹幕数")
n=1//进行excel最初列的设置
url = "https://www.bilibili.com"
fox = webdriver.Firefox()
//安装什么浏览器的内核就用什么浏览器
wait = WebDriverWait(fox,10)
//设置最大的等待时间是多少
try:
    total = search()
    print(total)
    for i in range(1, int(total)+1)://
这里用获得的最大页数控制循环次数,因为前面以及爬取了第一页因此从1开始
        next_page(i)
finally:
    fox.close()
data.save(u"菜虚鲲打篮球.xls")

效果图如下:
刚开始的时候弹出了登录框:

随后进行刷新:

然后开始爬取:


最后爬取的文件和内容:


PS:这里选中元素也可以使用XML,但是无论CSS选择器还是XML都能在定位好元素后,对定位元素点右键复制,能够
直接复制CSS选择器和XML不需要自行填写

评论区(暂无评论)

这里空空如也,快来评论吧~

我要评论