I made this code to download SDS for updating my CAS list.
After few cycle of this code, The error screenshot appears.
It shows only [].
Is that a prevent system for bot?
After few hours the site works again. How can I avoid this screen?
Is thre any recommendation for download SDS?
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import os
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# PDF 파일이 자동으로 열리지 않고 다운로드 되도록 설정
from webdriver_manager.chrome import ChromeDriverManager
# Chrome 옵션 설정
options = webdriver.ChromeOptions()
options.add_experimental_option("prefs", {
"download.default_directory": "C:\Users\lag\OneDrive\바탕 화면\MSDS\Ald\", # 다운로드 경로 설정
"download.prompt_for_download": False, # 다운로드 시 프롬프트 띄우지 않기
"plugins.always_open_pdf_externally": True, # 외부 PDF 뷰어를 사용하여 자동으로 파일 열기
"safebrowsing.enabled": True,
"profile.content_settings.exceptions.automatic_downloads.*.setting": 1
})
# ChromeDriverManager를 통해 ChromeDriver를 자동으로 설치하고 경로를 설정
# Service 객체를 사용하여 드라이버 서비스를 정의합니다.
service = Service(ChromeDriverManager().install())
# 수정된 생성자 인자를 사용하여 ChromeDriver 인스턴스 생성
driver = webdriver.Chrome(service=service, options=options)
wait = WebDriverWait(driver, 10)
CAS_list = ["100-01-6", "100-09-4", "100-20-9", "100-21-0"]
first_execution = True
def wait_for_downloads(download_path):
"""
주어진 경로에서 모든 파일 다운로드가 완료될 때까지 대기합니다.
파일 다운로드가 완료되면, 임시 다운로드 파일이 사라질 때까지 기다립니다.
"""
while any([filename.endswith('.crdownload') for filename in os.listdir(download_path)]):
time.sleep(1) # 잠시 대기하여 파일 다운로드가 완료될 수 있도록 합니다.
def rename(CAS):
try:
download_path = "C:\Users\lag\OneDrive\바탕 화면\MSDS\Ald\" # 파일 다운로드 경로 설정
wait_for_downloads(download_path) # 모든 다운로드가 완료될 때까지 대기
# 파일 이름 변경 로직
os.chdir(download_path) # 다운로드 디렉토리로 이동
files = os.listdir(download_path) # 디렉토리 파일 리스트
downloaded_file = max([f for f in files], key=os.path.getctime) # 가장 최근에 다운로드된 파일 찾기
# .crdownload 확장자를 가진 파일이 없을 경우, 파일 이름 변경
if not downloaded_file.endswith('.crdownload'):
new_file_name = f"{CAS}.pdf"
os.rename(downloaded_file, new_file_name) # 파일 이름 변경
except:
pass
def CAS_Browsing(CAS):
global first_execution
driver.get('https://www.sigmaaldrich.com/KR/ko/search')
driver.maximize_window()
if first_execution:
cookie_button = wait.until(EC.visibility_of_element_located((By.ID, 'onetrust-accept-btn-handler')))
cookie_button.click() # 쿠키 수락 버튼 클릭
first_execution = False
element = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="type"]')))
element.click()
element = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="menu-type"]/div[3]/ul/li[2]')))
element.click()
element = wait.until(EC.visibility_of_element_located((By.ID, 'term')))
element.send_keys(CAS)
element = wait.until(EC.visibility_of_element_located((By.ID, 'advanced-search-submit')))
element.click() #검색 Submit
try:
element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[starts-with(@id, 'sds-SIGALD')]")))
element.click()
except:
element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[starts-with(@id, 'sds-ALDRICH')]")))
element.click()
try:
driver.find_element(By.XPATH, "//*[@id='sds-link-KO']").click()
except:
driver.find_element(By.XPATH, "//*[@id='sds-link-EN']").click()
time.sleep(1)
rename(CAS)
try:
# 현재 창 핸들 저장
main_window_handle = driver.current_window_handle
# 모든 창 핸들 가져오기
all_window_handles = driver.window_handles
# 두 번째 탭으로 이동
second_tab_handle = all_window_handles[1]
driver.switch_to.window(second_tab_handle)
# 작업 수행 후 두 번째 탭 닫기
driver.close()
# 다시 원래 창으로 전환
driver.switch_to.window(main_window_handle)
except:
pass
for CAS in CAS_list:
CAS_Browsing(CAS)
driver.quit()
Error Screenshot
I want to operate normally with 1000 CAS Numbers.
New contributor
Hyunkyu Cho Laggom is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.