美文网首页
【爬虫成长之路】(四)【大众点评】selenium登录+requ

【爬虫成长之路】(四)【大众点评】selenium登录+requ

作者: keep1234quiet | 来源:发表于2021-04-21 12:10 被阅读0次

    本系列文章共十篇:

    【爬虫成长之路】(一)爬虫系列文章导读
    【爬虫成长之路】(二)各篇需要用到的库和工具
    【爬虫成长之路】(三)【大众点评】selenium爬虫
    【爬虫成长之路】(四)【大众点评】selenium登录+requests爬取数据
    【爬虫成长之路】(五)【大众点评】浏览器扫码登录+油猴直接爬取数据
    【爬虫成长之路】(六)【大众点评】mitmproxy中间人代理爬虫
    【爬虫成长之路】(七)【大众点评】PC微信小程序+requests爬取数据
    【爬虫成长之路】(八)【大众点评】安卓APP爬虫

    本文需要用到的工具:浏览器F12控制台
    本文需要用到的库:seleniumbs4requestsjson

    爬取目标数据:

    1. 指定城市的店铺列表及其评分数据
    2. 指定店铺下的用户评论数据

    一、需求分析

    这一篇总共需要爬取两个页面的数据,分别是:

    1. 某城市的店铺列表页面
    2. 某店铺的评论列表页面

    二、获取目标页面的URL

    这里获取这里获取的URL同【爬虫成长之路】(三)【大众点评】selenium爬虫一致,故不再介绍如何提取。相应的URL如下:

    # 登录URL
    https://account.dianping.com/login?redir=http%3A%2F%2Fwww.dianping.com%2F
    
    # 店铺列表URL
    http://www.dianping.com/guangzhou/ch10/p2
    
    # 评论详情URL
    http://www.dianping.com/shop/G8Ieq52Y02jBiXP8/review_all/p2
    

    三、分析文档结构,定位元素位置

    这里也同【爬虫成长之路】(三)【大众点评】selenium爬虫一致,没有变化,故不再作重复介绍。

    四、遇到的问题

    前面【爬虫成长之路】(三)【大众点评】selenium爬虫提到,selenium的缺点是速度太慢了,所以这一篇我们来考虑如何改善这个问题。

    我们知道,selenium之所以慢,是因为其操作依赖于浏览器,获取数据的过程中,浏览器启动慢,打开页面的过程中往往会加载其他无关的页面,具体速度取决于最后一个加载完成的URL,性能十分低下,所以我们这里改用requests来提升爬取速度,但前面也说过,大众点评的反爬技术在国内绝对是前几名的,系统的风控也十分严格。

    登录方式有三种:

    1. 扫码登录
    2. 手机验证码登录
    3. 账号密码登录

    现在大部分网站都是采用这几种方式去登录的。如果我们要做到全自动,就必须解决自动登录的问题,所以这里只能选择第三种账号密码登录的方式,然而这种方式却又是风控最严的,非常容易触发风控,触发风控后轻则出现各类验证码,重则直接限制账号登录。在爬取的过程中,遇到的验证码种类多样,应该还没有全部出来,所以要处理验证码是一件非常费劲的事。其实不光是验证码,登录过程中还有许多的参数会用JS加密,而JS又大又被混淆了,所以处理起来并不容易。如下是测试过程中遇到的风控和部分验证码:

    风控&验证码

    五、解决方案

    利用selenium获取cookie,使用requests提高爬取速度

    如果需要的爬取的数据量不大,或者仅仅是用来学习爬虫技术,在第一关登录时就花费如此多的精力是不值得的,所以我们选择使用selenium手机扫码登录,再将登录成功后的cookie复制到requests,这样就也可避开复杂的登录验证过程。

    为了避免频繁登录导致被封账号,可以将cookie先缓存下来,下次启动直接从文件中读取。

    关键代码如下:

    driver = webdriver.Chrome()
    cookie = {cookie['name']: cookie['value'] for cookie in driver.get_cookies()}
    
    session = requests.session()
    session.headers.clear()
    session.cookies.update(cookie)
    

    完整代码如下:

    # -*- coding: utf-8 -*-
    # @Time    : 2021/4/21 10:11
    # @Author  : keep1234quiet
    # @FileName: 04.selenium_requests_spider.py
    # @Software: PyCharm
    # @Blog    : https://www.jianshu.com/u/2fc23add985d
    
    import random
    import requests
    import json
    from selenium import webdriver
    from time import sleep
    from bs4 import BeautifulSoup as BS
    
    
    def login():
        """
        登录函数
        """
        login_url = 'https://account.dianping.com/login?redir=http%3A%2F%2Fwww.dianping.com%2F'
        driver.get(login_url)   # 打开登录页面,手动扫码登录
    
        while True:
            try:
                driver.find_element_by_class_name('login-container')  # 还能找到"请登录"
                sleep(2)
            except:
                driver.find_element_by_class_name('countDown')  # 登录成功
                break
    
        print('登录成功')
    
    
    def process_cookie(refresh_cookie=True):
        """
        处理cookie,将driver 的 cookie复制到 requests,并把cookie保存下来供下次使用
        :param refresh_cookie: 是否从selenium更新cookie
        :return:
        """
        headers = {
            'User-Agent': UA,
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'Upgrade-Insecure-Requests': '1',
            'Cache-Control': 'max-age=0',
        }
        session.headers.update(headers)
        # 将selenium中的cookie复制到requests.session()中
        if refresh_cookie:
            cookie = {cookie['name']: cookie['value'] for cookie in driver.get_cookies()}
            # 将获取到的cookie保存下来,避免重复获取
            with open('cookie/03.cookies.txt', 'w') as f:
                f.write(json.dumps(driver.get_cookies()))
            driver.quit()
            print('从selenium更新cookie')
        else:
            with open('cookie/03.cookies.txt', 'r') as f:
                cookies = json.loads(f.read())
                cookie = {_cookie['name']: _cookie['value'] for _cookie in cookies}
            print('从本地缓存更新cookie')
        session.cookies.update(cookie)
    
    
    def fetch_shoplist(page_num=1):
        """
        获取美食分区下的店铺信息
        """
        city = 'guangzhou'
        food_shop_url = f'http://www.dianping.com/{city}/ch10'  # /p1~
        shop_info = []
        for i in range(1, page_num + 1):
            # driver.get(food_shop_url + f'/p{i}')
            res = session.get(food_shop_url + f'/p{i}')
            # soup = BS(driver.page_source, 'lxml')
            soup = BS(res.content, 'lxml')
            page_shop = soup.find_all('div', class_='txt')
            for shop in page_shop:
                shop_info.append({
                    'shopid': shop.a['data-shopid'],
                    'name': shop.a.text.strip(),
                    'score': shop.find('div', class_='nebula_star').text.strip()
                })
        return shop_info
    
    
    def fetch_comment(shopid='H7fXoNAkafmesfFG', page=1):
        """
        爬取指定店铺下的用户评论
        :param shopid: 店铺ID
        :param page: 页码
        :return: 解析后的评论信息
        """
        url = f'http://www.dianping.com/shop/{shopid}/review_all'
        if page != 1:
            url += f'/p{page}'
        # driver.get(url)
        # soup = BS(driver.page_source, 'lxml')
        res = session.get(url)
        soup = BS(res.text, 'lxml')
        comments = soup.find_all('div', class_='main-review')
        comment_list = []
        for item in comments:   # 遍历所有评论
            username = item.find('div', class_='dper-info').text.strip()
            items = item.find_all('span', class_='item')     # 各项评分
            detail_score = []
            for _item in items:
                detail_score.append(_item.text.strip())
            content = item.find('div', class_='review-words').text.strip()  # 获取到的评论不全,做了CSS加密
            comment_list.append({'username': username, 'item': detail_score, 'content': content})
        return comment_list
    
    
    if __name__ == '__main__':
        refresh_cookie = False
        UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'
    
        session = requests.session()
        session.headers.clear()
    
        if refresh_cookie:
            options = webdriver.ChromeOptions()
            options.add_argument(f'user-agent={UA}')
    
            options.add_experimental_option("excludeSwitches", ["enable-automation"])
            options.add_experimental_option('useAutomationExtension', False)
    
            # 没有配置环境变量的话需要填写Chromedriver的路径:webdriver.Chrome(executable_path="***")
            driver = webdriver.Chrome(options=options)
            driver.maximize_window()
    
            # 去掉window.navigator.webdriver字段,防止被检测出是使用selenium
            driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
                "source": """
                Object.defineProperty(navigator, 'webdriver', {
                  get: () => undefined
                })
              """
            })
    
            login()
        process_cookie(refresh_cookie)
        shop_info = fetch_shoplist()
        for _ in shop_info:
            print(_)
    
        shopid = shop_info[2]['shopid']  # 这里也可以用for来遍历,但要适当加延时
        comment_list = fetch_comment(shopid=shopid, page=1)
        # print(comment_list)
        for _ in comment_list:
            print(_)
    

    六、程序运行结果

    从爬取结果来看,和之前的【爬虫成长之路】(三)【大众点评】selenium爬虫爬取结果是基本一致的。

    爬取结果

    七、优缺点分析

    序号 优点 缺点
    1 程序编写较为简单 爬取过程中仍然会遇到验证码无法处理
    2 速度比第三篇文章中所采用的方法要快很多 遇到复杂的请求,参数生成十分复杂

    注:

    1. 如果您不希望我在文章提及您文章的链接,或是对您的服务器造成了损害,请联系我对文章进行修改;
    2. 本文仅爬取公开数据,不涉及到用户隐私;

    相关文章

      网友评论

          本文标题:【爬虫成长之路】(四)【大众点评】selenium登录+requ

          本文链接:https://www.haomeiwen.com/subject/mfzrnktx.html