https://www.drissionpage.cn/get_start/installation
https://www.drissionpage.cn/demos/functions/new_browser
DrissionPage 是一个基于 python 的网页自动化工具。
它既能控制浏览器,也能收发数据包,还能把两者合而为一。
可兼顾浏览器自动化的便利性和 requests 的高效率。
它功能强大,内置无数人性化设计和便捷功能。
它的语法简洁而优雅,代码量少,对新手友好。
最好安装4.0或以上的版本 因为4.0更新的很多实用的功能
pip install -U DrissionPage==4.0.0b10
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()
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
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()
# 查找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 方式查找元素 |
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()
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)
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)
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'))