1.浏览器 DrissionPage 自动化工具
https://www.drissionpage.cn/
https://www.drissionpage.cn/get_start/installation
https://www.drissionpage.cn/demos/functions/new_browser
DrissionPage 是一个基于 python 的网页自动化工具。
它既能控制浏览器,也能收发数据包,还能把两者合而为一。
可兼顾浏览器自动化的便利性和 requests 的高效率。
它功能强大,内置无数人性化设计和便捷功能。
它的语法简洁而优雅,代码量少,对新手友好。
2.本库采用全自研的内核,内置了 N 多实用功能,对常用功能作了整合和优化,对比 selenium,有以下优点:
-
无 webdriver 特征
-
无需为不同版本的浏览器下载不同的驱动
-
运行速度更快
-
可以跨 iframe 查找元素,无需切入切出
-
把 iframe 看作普通元素,获取后可直接在其中查找元素,逻辑更清晰
-
可以同时操作浏览器中的多个标签页,即使标签页为非激活状态,无需切换
-
可以直接读取浏览器缓存来保存图片,无需用 GUI 点击另存
-
可以对整个网页截图,包括视口外的部分(90以上版本浏览器支持)
-
可处理非
open
状态的 shadow-root
3.简单使用
最好安装4.0或以上的版本 因为4.0更新的很多实用的功能
1 | pip install -U DrissionPage==4.0.0b10 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import time from DrissionPage import WebPage, ChromiumOptions from DrissionPage.common import By url_list = [ "https://www.gansu.gov.cn/gsszf/c108889/xxgk_zc.shtml" , # "https://samfrew.com/download/Galaxy__A14__/hkyk/GTO/A145MUBS5BXB2/A145MOWO5BXB2", # "https://tls.browserleaks.com/json", ] for i in range ( len (url_list)): co = ChromiumOptions() # co.set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") # 设置路径 # co.set_local_port(9310) # co.auto_port() # 自动获取空闲端口 co.no_imgs( True ) # 不加载图片 co.mute( True ) # 静音 co.set_argument( '--start-maximized' ) # 设置启动时最大化 co.set_timeouts(base = 2 , script = 2 ) # 设置超时时间 单位秒 co.set_retry(times = 1 , interval = 0 ) # 设置连接失败时的重试操作 co.set_load_mode( 'eager' ) # 设置load_mode,可接收 'normal', 'eager', 'none' co.set_user_agent( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0" ) co.ignore_certificate_errors(on_off = False ) # 设置是否忽略证书错误 co.set_argument( '--headless=new' ) # 无头浏览器 page = WebPage(chromium_options = co) # page = WebPage() # 访问某一页的网页 page.get(url_list[i]) time.sleep( 1 ) page.refresh() time.sleep( 2 ) html = page.html # 获取页面标题 print (page.title) # 获取页面html print (page.html) print (url_list[i]) # page.quit() |
4.DrissionPage监听接口获取数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | from DrissionPage import WebPage, ChromiumOptions from DrissionPage.common import By from lxml import etree cp = ChromiumOptions().set_paths(browser_path = r "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" ) page = WebPage( "d" , chromium_options = cp) print ( "当前页面对象模式11" , page.mode) page.listen.start( "office/jsp/zdsswfaj/wwquery" ) page.get( "http://beijing.chinatax.gov.cn/bjsat/office/jsp/zdsswfaj/wwquery.jsp" , retry = 3 , interval = 2 , timeout = 15 ) page.ele( "text=东城" ).click() print (page.ele( "text:项查询结果" ).text.strip().rstrip( "页" ).strip()) for packet in page.listen.steps(): res_text = packet.response.body if packet.method = = "POST" : al_res = etree.HTML(res_text) print (packet.method, packet.request.postData, packet.url) for tr in al_res.xpath( "//tr" ): tds = [td.strip() for td in tr.xpath( ".//td/text()" )] print (tds) cur_page = page.ele( "text:项查询结果" ).text.strip().split( "/" )[ 0 ][ - 1 ] print (f "当前是弟{page.ele('text:项查询结果').text.strip().rstrip('页').strip()}" ) page( "text=下一页" ).click() # loc2 = (By.XPATH, xpath) # ele = page.ele(loc2) # ele.click() if cur_page = = "3" : break |
5.DrissionPage获取iframe获取数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import time from DrissionPage import WebPage, ChromiumOptions from DrissionPage.common import By url_list = [ # "https://www.gansu.gov.cn/gsszf/c108889/xxgk_zc.shtml", # "https://samfrew.com/download/Galaxy__A14__/hkyk/GTO/A145MUBS5BXB2/A145MOWO5BXB2", # "https://tls.browserleaks.com/json", "http://beijing.chinatax.gov.cn/bjsat/office/jsp/zdsswfaj/wwquery.jsp" , ] for i in range ( len (url_list)): co = ChromiumOptions() # co.set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") # 设置路径 co.set_local_port( 9313 ) # co.auto_port() # 自动获取空闲端口 co.no_imgs( True ) # 不加载图片 co.mute( True ) # 静音 co.set_argument( '--start-maximized' ) # 设置启动时最大化 co.set_timeouts(base = 2 , script = 2 ) # 设置超时时间 单位秒 co.set_retry(times = 1 , interval = 0 ) # 设置连接失败时的重试操作 co.set_load_mode( 'normal' ) # 设置load_mode,可接收 'normal', 'eager', 'none' co.set_user_agent( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0" ) # co.ignore_certificate_errors(on_off=False) # 设置是否忽略证书错误 # co.set_argument('--headless=new') # 无头浏览器 page = WebPage(chromium_options = co) # page.set.auto_handle_alert(all_tabs=True) # 自动处理弹窗 # page = WebPage() # 访问某一页的网页 page.get(url_list[i]) time.sleep( 1 ) page.refresh() # time.sleep(2) print ( "XPATH 点击" ) # loc2 = (By.XPATH, '//*[@id="2014"]/tbody/tr/td/a') ele = page.ele( 'x://*[@id="2014"]/tbody/tr/td/a' ).click() # ele = page.ele('t:div').click() # page.ele("text=东城").click() print ( "XPATH 点击结束" ) time.sleep( 1 ) html = page.html # 获取页面标题 print (page.title) # 获取页面html # print(html) print ( "北京洪瑞厚通贸易有限公司" in page.html) print ( "北京洪瑞厚通贸易有限公司" in page.get_frame( '#rightiframe' ).html) print ([ "北京洪瑞厚通贸易有限公司" in iframe.html for iframe in page.get_frames( 't:iframe' )]) print (url_list[i]) # page.quit() |
6.简化写法
1 2 3 4 5 6 7 8 9 10 11 | # 查找tag为div的元素 ele = page.ele( 'tag:div' ) # 原写法 ele = page( 't:div' ) # 简化写法 # 用xpath查找元素 ele = page.ele( 'xpath://xxxxx' ) # 原写法 ele = page( 'x://xxxxx' ) # 简化写法 # 查找text为'something'的元素 ele = page.ele( 'text=something' ) # 原写法 ele = page( 'tx=something' ) # 简化写法 |
简化写法对应列表
原写法 | 简化写法 | 说明 |
---|---|---|
@id |
# |
表示 id 属性,简化写法只在语句最前面且单独使用时生效 |
@class |
. |
表示 class 属性,简化写法只在语句最前面且单独使用时生效 |
text |
tx |
按文本匹配 |
@text() |
@tx() |
按文本查找与 @ 或 @@ 配合使用时 |
tag |
t |
按标签类型匹配 |
xpath |
x |
用 xpath 方式查找元素 |
css |
c |
用 css selector 方式查找元素 |
7.实现无头浏览器/无痕隐身模式/访客模式/设置ua/设置指定端口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | from DrissionPage import ChromiumPage, ChromiumOptions from loguru import logger import platform if platform.system().lower() = = 'windows' : co = ChromiumOptions().set_paths(browser_path = r "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" ) else : co = ChromiumOptions() #.set_paths(browser_path=r"/opt/google/chrome/google-chrome") co.set_local_port( 9211 ) co.set_user_agent(user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36' ) # 设置ua co.headless( True ) # 设置无头加载 无头模式是一种在浏览器没有界面的情况下运行的模式,它可以提高浏览器的性能和加载速度 co.incognito( True ) # 无痕隐身模式打开的话,不会记住你的网站账号密码的 co.set_argument( '--guest' ) # 设置访客模式,不会记住你的网站账号密码的等cookie co.set_argument( '--no-sandbox' ) # 禁用沙箱 禁用沙箱可以避免浏览器在加载页面时进行安全检查,从而提高加载速度 默认情况下,所有Chrome 用户都启用了隐私沙盒选项 https://zhuanlan.zhihu.com/p/475639754 co.set_argument( "--disable-gpu" ) # 禁用GPU加速可以避免浏览器在加载页面时使用过多的计算资源,从而提高加载速度 # 创建浏览器对象 browser = ChromiumPage(co) # 创建对象 browser.get( "https://www.itjuzi.com/ipo" , retry = 3 , interval = 2 , timeout = 15 ) # 访问网 detail_links_all = [] for tr in browser.eles( "css:.el-table__row" ): tds = [td.text.strip() for td in tr.eles( "x:.//td" )[ 1 :]] company = tr.ele( "tag:a" ).text a_href = tr.ele( "tag:a" ).attr( "href" ) detail_links_all.append(a_href) logger.info(f "list_page_company is {company} , a_href is {a_href}" ) logger.success(f ">>>>>total_detail_urls is : {len(detail_links_all)}" ) browser.quit() |
8.drissionpage并发10倍速度爬取详情页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | from DrissionPage import ChromiumPage, ChromiumOptions from loguru import logger from concurrent.futures import ThreadPoolExecutor def detail_tab(d_url): tab = page.new_tab(d_url) compa = tab.ele( "css:.company-header-title" ).text tags = [tag.text for tag in tab.eles( "css:.company-tags-box a" )] logger.success(f ">>>>>detail_latest_tab : {compa} , tags: {tags}, tab_url : {tab.url}" ) tab.close() co = ChromiumOptions().set_paths(browser_path = r "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" ) co.set_user_agent(user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36' ) page = ChromiumPage(co) # 创建对象 page.get( "https://www.itjuzi.com/ipo" , retry = 3 , interval = 2 , timeout = 15 ) # 访问网 # 一次性拿到所有详情链接 detail_links_all = [] for tr in page.eles( "css:.el-table__row" ): tds = [td.text.strip() for td in tr.eles( "x:.//td" )[ 1 :]] company = tr.ele( "tag:a" ).text a_href = tr.ele( "tag:a" ).attr( "href" ) detail_links_all.append(a_href) logger.info(f "list_page_company is {company} , a_href is {a_href}" ) # detail_tab(a_href) logger.success(f ">>>>>total_detail_urls is : {len(detail_links_all)}" ) # # 单线程标签页操作 # for a_href in detail_links_all: # tab = page.new_tab(a_href) # # tab = page.latest_tab # company = tab.ele("css:.company-header-title").text # tags = [tag.text for tag in tab.eles("css:.company-tags-box a")] # logger.success(f">>>>>detail_latest_tab : {company} , tags: {tags}, tab_url : {tab.url}") # tab.close() # 多线程标签页操作 with ThreadPoolExecutor(max_workers = 10 ) as tp: tp. map (detail_tab, detail_links_all) |
9.浏览器渲染页面的方式,瑞数vmp反爬
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from DrissionPage import ChromiumPage, ChromiumOptions from lxml import etree co = ChromiumOptions().set_paths(browser_path = r "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" ) page = ChromiumPage(co) page.get( 'http://beijing.chinatax.gov.cn/bjsat/office/jsp/zdsswfaj/wwquery.jsp' , retry = 3 , interval = 2 , timeout = 15 ) # 访问网页 page.ele( 'text=东城' ).click() page.wait( 2 , 3 ) print ( "北京洪瑞厚通贸易有限公司" in page.html) # False print ( "iframe" , "北京洪瑞厚通贸易有限公司" in page.get_frame( 'x://table//table//iframe' ).html) # True print ( "iframe" , [ "北京洪瑞厚通贸易有限公司" in iframe.html for iframe in page.get_frames( 't:iframe' )]) # True iframe = page.get_frame( 'x://table//table//iframe' ) for tr in iframe.eles( "x://tr" ): tds = [td.text for td in tr.eles( 'x://td' )] print (tds) |
10.dp爬虫自动化过阿里滑块实战
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import random import time from DrissionPage import ChromiumPage, ChromiumOptions co = ChromiumOptions() co.auto_port() page = ChromiumPage(co) def slide(): ss = 253 page.wait.ele_loaded( "x://span[contains(@id,'nc_1_n1z')]" ) page.ele( "x://span[contains(@id,'nc_1_n1z')]" ).hover() page.actions.hold( "x://span[contains(@id,'nc_1_n1z')]" ) page.actions.move(ss, duration = random.random()) time.sleep(random.random()) # ac.release("x://span[contains(@id,'nc_1_n1z')]") page.get( 'http://purchase.ecrrc.com/order-0/list-0-0-0-1.html' ) if page.ele( 'text:请按住滑块,拖动到最右边' ): slide() for row in page.eles( 'x://a[@class="p-l-m-title"]' ): print ( "获取到的标题与链接》》》" , row.text, row.attr( 'href' )) |
11.查看浏览器特征 打开这个网站
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)