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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
| from playwright.sync_api import sync_playwright
import random
import time
class BrowserSimulator:
def __init__(self):
self.playwright = sync_playwright().start()
self.browser = None
def launch_browser(self, headless=True, proxy=None):
"""启动浏览器"""
launch_options = {
'headless': headless,
'args': [
'--disable-blink-features=AutomationControlled',
'--disable-dev-shm-usage',
'--no-sandbox',
]
}
if proxy:
launch_options['proxy'] = {'server': proxy}
self.browser = self.playwright.chromium.launch(**launch_options)
return self.browser
def create_stealth_context(self):
"""创建隐身上下文"""
context = self.browser.new_context(
viewport={'width': 1920, 'height': 1080},
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
locale='zh-CN',
timezone_id='Asia/Shanghai',
)
# 注入反检测脚本
context.add_init_script("""
// 覆盖 navigator.webdriver
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
});
// 覆盖 navigator.plugins
Object.defineProperty(navigator, 'plugins', {
get: () => [1, 2, 3, 4, 5]
});
// 覆盖 navigator.languages
Object.defineProperty(navigator, 'languages', {
get: () => ['zh-CN', 'zh', 'en']
});
// Chrome 检测绕过
window.chrome = {
runtime: {}
};
""")
return context
def simulate_human_behavior(self, page):
"""模拟人类行为"""
# 随机滚动
page.evaluate("""
() => {
window.scrollTo({
top: Math.random() * document.body.scrollHeight,
behavior: 'smooth'
});
}
""")
time.sleep(random.uniform(0.5, 2))
# 随机鼠标移动
page.mouse.move(
random.randint(100, 500),
random.randint(100, 500)
)
time.sleep(random.uniform(0.2, 0.5))
def scrape_with_stealth(self, url):
"""隐身爬取"""
context = self.create_stealth_context()
page = context.new_page()
try:
page.goto(url, wait_until='networkidle')
self.simulate_human_behavior(page)
content = page.content()
return content
finally:
page.close()
context.close()
|