DrissionPage爬虫实例

今天发现了一个非常好用的库,DrissionPage。可以操控实际的浏览器,不像selenium一样需要配合浏览器的驱动版本。直接操控谷歌浏览器,非常牛逼。

话不多说,直接干!

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time

from DrissionPage import ChromiumOptions
from DrissionPage import ChromiumPage


class WB:
    def __init__(self):
        co = ChromiumOptions()
        # - 浏览器如果是下载的 exe 文件安装的,不用写。
        # co.set_paths(browser_path=r'D:\Chrome\chrome.exe')
        self.wb = ChromiumPage(co)


    def click_by_xpath(self,_type,path,button='',max_retry=40):
        """
        根据xpath定位元素,并且点击该元素
        如果定位失败,自动重试,重试间隔为5秒
        """
        count = 0
        while count <= max_retry:
            count += 1
            try:
                clickobj = self.wb.ele(f'{_type}:{path}')
                clickobj.click()
                return
            except:
                print(f'继续等待,即将点击{button}')
                time.sleep(5)
        raise ValueError


    def getPageHtml(self):
        """获取页面上的网页源码"""
        return self.wb.html



    def scroll_to_button(self,path):
        """操作滚动条,滚动到页面一半的位置"""
        self.wb.ele(f'c:{path}').scroll.to_half()

还可以指定url监听网络交互,就是开发者模式下,network里的交互数据理论上都能拿下来!!!

from DrissionPage import Chromium

tab = Chromium().latest_tab
tab.listen.start(targets='/janus/api/auth')  # 开始监听,指定获取包含该文本的数据包
tab.get('https://mms.pinduoduo.com/mallcenter/info/entry/index')  # 访问网址
input('===>')

i = 0
for packet in tab.listen.steps():
    print(packet.url)  # 打印数据包url
    print(packet.response.headers)  # 打印数据包url

藏在最后的宝藏:

DrissionPage官网

你可能感兴趣的:(爬虫,1024程序员节,爬虫,python)