發表文章

目前顯示的是 6月, 2021的文章

[變數] 使用全域變數

##global variable here ## myvar = 'test1' def my_func1():      ##it will print the content of global  variable ##     print( myvar ) my_func1() def my_func2():     myvar = ' test2 '      ##it will print the content of local  variable ##     print( myvar ) my_func2() ##the content of global  variable does not change ## print( myvar ) def my_func3():      ##use global variable in function like this ##      global  myvar      myvar = ' test3'     print( myvar ) my_func3() ##the content of global  variable will be changed in the function ## print( myvar )

[臨時檔] 開啟臨時檔

##import## import tempfile ##generate  temporary file and write ## with  tempfile.NamedTemporaryFile( suffix='.txt',  prefix='tmp',   dir='d:\\cykuo\\tmp' ,  delete=False) as f:     print(f.name)     f.write( b 'test data')      #若沒有加 b , 會出現 Excption:     #  TypeError: a bytes-like object is required, not 'str'

[臨時檔] 不需實際開臨時檔就取得檔名

  ##import## import tempfile ##get  temporary file name only ## tmp_filename = next(tempfile._get_candidate_names())

[例外處理] 發出例外加訊息

raise  Exception ('ERROR Messages...') #catch and print the exception message try :     (...codes...) except Exception as e:      print(e)

[Web擷取功能] CPATCHA 破解基礎方法

##install## #install  tesseract-ocr #python -m pip install Pillow #python -m pip install  pytesseract #python -m pip install selenium ##import## #from PIL import Image #from pytesseract import image_to_string #from selenium import webdriver ##create browser driver and save screenshot## # browser = webdriver. Ie ( driver_path ) # browser = webdriver. Chrome ( driver_path ) # browser = webdriver. Firefox ( driver_path ) # browser .get( url ) # browser .set_window_size(800, 600) # option driver.save_screenshot( screenshot_filepath ) ##get CAPTCHA image element## #element =  browser .find_element_by_xpath('//*[@id="form1"]/img') location = element.location size = element.size ##functions## def get_captcha_text(location, size):      pytesseract.pytesseract.tesseract_cmd = pytesseract_path      img = Image.open( screenshot_filepath )      left = location['x']      top = location['y']      right = locatio...

[Web擷取功能] 取得 WebElement 的 HTML 屬性值

##install## #python -m pip install selenium ##import## #from selenium import webdriver ##create browser driver## # browser = webdriver. Ie ( driver_path ) # browser = webdriver. Chrome ( driver_path ) # browser = webdriver. Firefox ( driver_path ) # browser .get( url ) ##functions## def get_element_attribute(id, attribute_name):     elmt = browser.find_element_by_id('org')     return elmt. get_attribute ( attribute_name )