-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTII_Automation.py
More file actions
248 lines (200 loc) · 8.15 KB
/
Copy pathTII_Automation.py
File metadata and controls
248 lines (200 loc) · 8.15 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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# 導入所需的套件
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import pytesseract
from PIL import Image, ImageEnhance, ImageFilter
import numpy as np
import cv2
import io
import requests
import time
import os
import urllib3
# 忽略 SSL 警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 設定 Tesseract 執行檔路徑
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
def setup_image_folder():
"""建立圖片存放資料夾"""
# 獲取目前腳本的完整路徑
script_dir = os.path.dirname(os.path.abspath(__file__))
# 在腳本目錄下建立 images 資料夾
image_folder = os.path.join(script_dir, 'images')
# 如果資料夾不存在,就建立它
if not os.path.exists(image_folder):
os.makedirs(image_folder)
print(f"已建立圖片資料夾: {image_folder}")
return image_folder
def setup_driver():
"""設定並返回 Chrome WebDriver"""
options = webdriver.ChromeOptions()
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument('--ignore-certificate-errors')
return webdriver.Chrome(options=options)
def click_initial_search(driver):
"""點擊初始搜尋按鈕"""
try:
# 訪問初始頁面
driver.get("https://insprod.tii.org.tw/")
print("已訪問初始頁面")
# 等待並點擊第一個搜尋按鈕 (使用ID優先)
wait = WebDriverWait(driver, 10)
search_button = wait.until(EC.element_to_be_clickable((By.ID, "Go22")))
print("找到搜尋按鈕")
search_button.click()
print("已點擊搜尋按鈕")
# 等待頁面加載
time.sleep(2)
return True
except TimeoutException:
print("等待初始搜尋按鈕超時")
return False
except Exception as e:
print(f"點擊初始搜尋按鈕時發生錯誤: {str(e)}")
return False
def process_image(img_path):
"""最小程度處理圖片,保持原始藍色"""
try:
# 讀取圖片
img = cv2.imread(img_path)
if img is None:
print(f"無法讀取圖片: {img_path}")
return None
# 稍微增強對比度但保持原色
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
# 輕微增強亮度通道
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
enhanced_l = clahe.apply(l)
# 合併回去
enhanced = cv2.merge([enhanced_l, a, b])
result = cv2.cvtColor(enhanced, cv2.COLOR_LAB2BGR)
# 稍微放大一點點
scale = 1.2
result = cv2.resize(result, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
return result
except Exception as e:
print(f"圖片處理過程中發生錯誤: {str(e)}")
return None
def get_captcha_text(driver, debug_mode=True):
"""處理驗證碼圖片並進行辨識"""
image_folder = setup_image_folder()
temp_img_path = os.path.join(image_folder, "captcha_temp.png")
processed_path = os.path.join(image_folder, "processed_captcha.png")
try:
# 獲取驗證碼圖片
full_img_url = "https://insprod.tii.org.tw/bmp.ashx"
print(f"正在下載驗證碼圖片...")
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/91.0.4472.124',
'Referer': 'https://insprod.tii.org.tw/Query.aspx'
}
response = requests.get(
full_img_url,
headers=headers,
verify=False,
timeout=10
)
if response.status_code != 200:
print(f"下載圖片失敗,狀態碼: {response.status_code}")
return None
# 儲存原始圖片
with open(temp_img_path, "wb") as f:
f.write(response.content)
print(f"原始驗證碼圖片已保存至: {temp_img_path}")
# 處理圖片
processed_image = process_image(temp_img_path)
if processed_image is None:
print("圖片處理失敗")
return None
cv2.imwrite(processed_path, processed_image)
print(f"處理後的圖片已保存至: {processed_path}")
# 使用不同的 OCR 配置嘗試識別
configs = [
'--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789',
'--psm 8 --oem 3 -c tessedit_char_whitelist=0123456789',
'--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789'
]
results = []
for i, config in enumerate(configs, 1):
try:
# 直接使用原圖進行識別
img = Image.open(processed_path)
text = pytesseract.image_to_string(img, config=config).strip()
digits = ''.join(filter(str.isdigit, text))
print(f"OCR配置 {i}: {config}")
print(f"識別結果: {text}")
print(f"過濾後數字: {digits}")
if len(digits) == 4:
results.append(digits)
except Exception as e:
print(f"OCR配置 {i} 識別失敗: {str(e)}")
if results:
most_common = max(set(results), key=results.count)
print(f"最終選擇的識別結果: {most_common}")
return most_common
print("沒有有效的識別結果")
return None
except Exception as e:
print(f"驗證碼識別過程中發生錯誤: {str(e)}")
import traceback
traceback.print_exc()
return None
def fill_and_submit_form(driver, captcha_text):
"""填寫並提交表單"""
try:
# 等待輸入框出現
wait = WebDriverWait(driver, 10)
input_field = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "input[name='bmpC3']"))
)
# 輸入驗證碼
input_field.clear()
input_field.send_keys(captcha_text)
print(f"已輸入驗證碼: {captcha_text}")
# 找到並點擊提交按鈕
submit_button = driver.find_element(By.CSS_SELECTOR, "input[name='Go2222']")
submit_button.click()
return True
except Exception as e:
print(f"表單提交錯誤: {str(e)}")
return False
def main():
"""主程式"""
driver = None
# driver = None 的設置有兩個主要目的:
# 初始化變數,確保 finally 區塊可以檢查 driver 是否存在
# 在異常情況下安全地關閉瀏覽器:如果不設置 driver = None,在 setup_driver() 失敗時 finally 區塊會拋出 NameError。
try:
# 設置驅動
driver = setup_driver()
# 步驟1: 點擊初始搜尋按鈕
if not click_initial_search(driver):
print("初始搜尋按鈕點擊失敗")
return
print("成功進入查詢頁面")
time.sleep(2) # 等待頁面完全加載
# 步驟2: 處理驗證碼和表單
captcha_text = get_captcha_text(driver, debug_mode=True)
if captcha_text and len(captcha_text) == 4: # 確保是4位數
print(f"識別到的驗證碼: {captcha_text}")
# 填寫並提交表單
if fill_and_submit_form(driver, captcha_text):
print("表單提交成功")
else:
print("表單提交失敗")
else:
print(f"驗證碼識別失敗或格式不正確: {captcha_text}")
except Exception as e:
print(f"執行過程中發生錯誤: {str(e)}")
finally:
# 等待一下看結果
time.sleep(5)
if driver:
driver.quit()
if __name__ == "__main__":
main()