1 of 28

Ch3 – PyAutoGUI #2 - Selenium

2 of 28

โจทย์จากบทที่ 2

- ลองค้นหาข้อมูลด้วย keyword เช่น ค้นหาเรทสกุลเงิน � sgd to thb , usd to thb, yuan to thb, jpy to thb

- ลองสั่ง capture หน้าจอผลลัพธ์ที่ค้นหาได้

3 of 28

ตัวอย่าง workshop: เขียนโปรแกรมจับภาพหน้าจอ

import pyautogui

import time

import webbrowser

import pyperclip

url = 'https://www.google.com'

webbrowser.open(url) # สั่งเปิดเว็บไซต์ google

keyword = ‘ประเทศไทย’

pyperclip.copy(keyword)

time.sleep(5)

#pyautogui.write(‘ประเทศไทย’, interval=0.25) # สั่งพิมพ์

pyautogui.hotkey(‘ctrl’,’v’)

pyautogui.press('enter’)

time.sleep(2)

pyautogui.screenshot(‘capture.png’)

ติด error pillow ให้ลองใช้คำส่ง pip install --upgrade pillow

4 of 28

datetime

5 of 28

strftime()

6 of 28

https://strftime.org/

7 of 28

8 of 28

for loop

9 of 28

pyautogui.scroll()

10 of 28

การใช้ f-strings จัดรูปแบบข้อความ

11 of 28

Selenium คืออะไร

  • Selenium คือ เครื่องมือ (framework) สำหรับควบคุมเว็บเบราว์เซอร์แบบอัตโนมัติ (Web Automation)
  • ใช้ในการทดสอบเว็บแอปพลิเคชัน (Web Testing)
  • ทำงานอัตโนมัติบนเว็บ (Web Automation / RPA)
  • เก็บข้อมูลจากเว็บ (Web Scraping – ในกรณีที่เว็บอนุญาต)

12 of 28

Selenium ใช้ทำอะไรได้บ้าง

  • เปิดเว็บไซต์อัตโนมัติ (Chrome, Edge, Firefox ฯลฯ)
  • กรอกฟอร์ม คลิกปุ่ม เลือกเมนู
  • ทดสอบการทำงานของระบบเว็บ (Login, CRUD, Workflow)
  • จำลองพฤติกรรมผู้ใช้จริง (เหมือนคนใช้งานเบราว์เซอร์)

13 of 28

ภาษาโปรแกรมที่รองรับ�

  • Python (นิยมมาก)
  • Java
  • C#
  • JavaScript
  • Ruby

14 of 28

ส่วนประกอบหลักของ Selenium�

  • Selenium WebDriver�ใช้ควบคุมเบราว์เซอร์โดยตรง (ส่วนที่นิยมใช้มากที่สุด)

  • Selenium IDE�เครื่องมืออัด (Record) และเล่นซ้ำ (Playback) การทำงานบนเว็บ

  • Selenium Grid�ใช้รันทดสอบหลายเครื่อง / หลายเบราว์เซอร์พร้อมกัน

15 of 28

https://selenium-python.readthedocs.io/

16 of 28

ติดตั้ง selenium�ที่ terminal ของ vs code ใช้คำสั่ง�pip install selenium

17 of 28

ติดตั้ง chrome driver

18 of 28

19 of 28

20 of 28

เลือก chrome driver ให้เหมาะสมกับเครื่องที่จะติดตั้ง

21 of 28

extract chromedriver zip ไฟล์

แล้วให้นำ chromedriver.exe ไปวางไว้โฟลเดอร์เดียวกับโปรเจคที่ต้องการจะใช้งาน

22 of 28

สร้างไฟล์ใหม่ชื่อ openweb.py

23 of 28

24 of 28

25 of 28

คลิ๊กขวาที่ช่อง search แล้วกด inspect

26 of 28

27 of 28

28 of 28