简体   繁体   中英

Can I tick a checkbox using BeautifulSoup / Selenium?

I am learning to use Selenium & BeautifulSoup and am struggling with the following:

I have a list of product codes:

['1242737-011', '4232345-015', '5673845-013']

for which I need to tick the checkbox in the following html code. So in this case only the first checkbox would get selected (1242737-011)

<tr class="dividebelow">
    <td>&nbsp;&nbsp;&nbsp;1242737-011&nbsp;&nbsp;</td>
    <td>x small</td>
    <td>16</td>
    <td>21</td>
    <td>0</td>
    <td>0</td>
    <td>

        <input class="select_products__product_table_1242737_checkbox select_products__variants_checkbox" name="variants" value="11866208" type="checkbox">

    </td>
</tr>

    <tr class="dividebelow">
    <td>&nbsp;&nbsp;&nbsp;1242737-012&nbsp;&nbsp;</td>
    <td>small</td>
    <td>36</td>
    <td>65</td>
    <td>1</td>
    <td>0</td>
    <td>

        <input class="select_products__product_table_1242737_checkbox select_products__variants_checkbox" name="variants" value="11866209" type="checkbox">

    </td>
</tr>                      

Any idea how this can be done? Thanks a lot!

Selenium has many functions to search element and click it to check it.

You can use find_element_by_name(name) or find_element_by_xpath(...) when you want to use complex xpath


Example code for page with three checkboxes

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox

import selenium.webdriver

url = 'https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox'

#driver = selenium.webdriver.Chrome()
driver = selenium.webdriver.Firefox()
driver.get(url)

# checkboxes are in <iframe> so I have to switch frame
driver.switch_to.frame(0)

# click checkboxes using names
for name in ["vehicle1", "vehicle2", "vehicle3"]:
    items = driver.find_element_by_name(name)
    #items = driver.find_element_by_xpath(f'//input[@name="{name}"]')
    items.click()

# click "Submit"
#button = driver.find_element_by_xpath('//input[@type="submit"]')
button = driver.find_element_by_xpath('//input[@value="Submit"]')
button.click()        

BTW: BeautifulSoup will be useless because it can't change checkboxes in web browser and click button to sends it to server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM