-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_chrome.py
More file actions
63 lines (48 loc) · 1.86 KB
/
test_chrome.py
File metadata and controls
63 lines (48 loc) · 1.86 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
import time
import pytest
from chrome import start_chrome, shutdown_chrome
from playwright.sync_api import sync_playwright
from ext_browser_context import ExtBrowserContext
from playwright_stealth.stealth import Stealth
def test_start_chrome():
"""测试启动 Chrome 浏览器"""
debug_port = 9222
chrome_cmd, _ = start_chrome(debug_port)
time.sleep(2)
shutdown_chrome(chrome_cmd, f"http://localhost:{debug_port}")
def test_visit_zhipin():
debug_port = 9222
# 使用 Playwright 连接到 Chrome
with Stealth().use_sync(sync_playwright()) as p:
browser = p.chromium.connect_over_cdp(f"http://localhost:{debug_port}")
# 获取或创建浏览器上下文
contexts = browser.contexts
if contexts:
context = contexts[0]
else:
context = browser.new_context()
# 创建新页面
page = context.new_page()
# 关键:删除 navigator.webdriver 属性(很多网站检测这个)
page.add_init_script("""
delete navigator.__proto__.webdriver;
// 可选:覆盖其他指纹
window.chrome = { runtime: {} };
Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh'] });
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] });
""")
# 访问目标网址
url = "https://www.zhipin.com/gongsi/job/5d627415a46b4a750nJ9.html?ka=company-jobs"
page.goto(url)
# 等待一段时间观察页面
time.sleep(10)
# 获取页面标题
title = page.title()
print(f"页面标题: {title}")
# 关闭页面
page.close()
# 断开连接
browser.close()
if __name__ == "__main__":
# test_start_chrome()
test_visit_zhipin()