场景
我们做自动化操作的时候,经常被浏览器检测为自动化测试工具,然后被各种制裁,例如:什么真人验证,什么同用不同源(意思是一个东西,网页上和自动化网页效果不一样),反复制裁,我就想能否有一个方案,不让浏览器知道是自动化工具在操作呢?
论证 求道
纠错
那我们就束手无策了吗?我谷歌了一下,很多人说加什么User-agent,什么浏览器xx,其实都是不正确的,因为那是针对请求的,并不是针对自动化操作的,自动化操作最重要义是什么?是替代无意义的重复劳动,那么这个行为一定是仿人的,那我们有什么办法呢?
灵感
这个时候我发现我打开了一个谷歌浏览器,然后进行同样的操作,拦截一个自动机浏览器,做一样的操作,他们得到的结果是截然不同的,我深深郁闷,如果能操作人为浏览器就好了!哎! 什么?操作人为浏览器???那我岂不是可以用远程控制做到,说干就干。
写了这个代码:
python
import subprocess
import random
import socket
#
# @Author: Herche Jane
# @Date: 2024-08-12
class ChromeController:
def __init__(self):
self.process = None
self.port = None
def find_free_port(self):
"""Find a free port by opening a temporary socket."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return port
def open_chrome(self):
"""Open Chrome browser with a free debugging port."""
try:
# 生成随机的未使用端口
self.port = self.find_free_port()
# Chrome 启动命令,路径使用双引号括起来
chrome_command = f'"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" --remote-debugging-port={self.port} --user-data-dir="xxx"'
# 启动 Chrome 浏览器
self.process = subprocess.Popen(chrome_command, shell=True)
return self.port
except Exception as e:
print(f"Error opening Chrome: {e}")
return -1
def close_chrome(self):
"""Close the Chrome browser if it's running."""
if self.process:
try:
self.process.terminate() # 结束 Chrome 进程
self.process.wait()
self.process = None
print("Chrome closed successfully.")
except Exception as e:
print(f"Error closing Chrome: {e}")
if __name__ == "__main__":
chrome_controller = ChromeController()
port = chrome_controller.open_chrome()
if port != -1:
print(f"Chrome started on port {port}")
else:
print("Failed to start Chrome.")
这就等于是人为打开而不是使用google driver打开的浏览器,我对其一番操作得到的结果果然和我手动操作的一模一样
行动和论证
我接下来使用自动化接管了这个浏览器,果然,一顿操作下来得到的结果和手动的一模一样
结论
必要情况下:使用命令打开 + 自动化接管方式 就可以解决大部分被制裁的问题