[파이썬] Selenium 폼 입력 및 제출

Selenium is a powerful tool for automating web browsers, allowing developers to interact with web pages, fill out forms, and submit them. In this blog post, we will explore how to use Python and Selenium to input data into forms and submit them.

Setting up Selenium

Before we can start using Selenium, we need to set it up in our Python environment. Here are the steps to install Selenium using pip:

pip install selenium

Additionally, you will need to download the appropriate WebDriver for the browser you are working with. WebDriver acts as a bridge between Selenium and the browser. For example, if you are using Chrome, download the ChromeDriver.

Importing necessary modules

To get started, we need to import the Selenium modules in our Python script. Here’s the import statement:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Creating a WebDriver instance

Next, we need to initialize a WebDriver instance. This will enable us to open a browser window and control it. Here’s an example for Chrome:

driver = webdriver.Chrome('path_to_chromedriver')

Make sure to provide the correct path to the chromedriver executable file.

Now, we can use the WebDriver instance to navigate to the web page containing the form. Simply call the get() method and pass the URL of the page:

driver.get('https://example.com/form')

Locating form elements

To input data into form fields, we need to find the appropriate web elements. This can be done using methods like find_element_by_id(), find_element_by_name(), or find_element_by_xpath().

input_field = driver.find_element_by_id('input_field')

Inputting data into form fields

Once we have located the form element, we can use the send_keys() method to input data into it:

input_field.send_keys('Hello, world!')

Submitting the form

After filling out the form, we can submit it by finding the submit button element and calling the click() method:

submit_button = driver.find_element_by_id('submit_button')
submit_button.click()

Complete example

Putting it all together, here’s a complete example:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome('path_to_chromedriver')
driver.get('https://example.com/form')

input_field = driver.find_element_by_id('input_field')
input_field.send_keys('Hello, world!')

submit_button = driver.find_element_by_id('submit_button')
submit_button.click()

driver.quit()

And that’s it! Now you know how to use Selenium in Python to input data into forms and submit them. Happy automating!