在python中使用selenium在页面中单击多个单选按钮时获取数据

2024-07-01 07:55:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个页面,上面有三个单选按钮。我希望我的代码连续单击这些按钮中的每一个,当它们被单击时,会显示一个值(mpn),我希望获得这个值。我能够为一个单选按钮编写代码,但我不明白如何创建一个循环,以便只更改这个按钮的值(值={1,2,3})

from selenium import webdriver
from bs4 import BeautifulSoup
driver = webdriver.Chrome(executable_path=r"C:\Users\Home\Desktop\chromedriver.exe")
driver.get("https://www.1800cpap.com/resmed-airfit-n30-nasal-cpap-mask-with-headgear")
soup = BeautifulSoup(driver.page_source, 'html.parser')

size=driver.find_element_by_xpath("//input[@class='product-views-option-tile-input-picker'and @value='2' ]")
size.click()
mpn= driver.find_element_by_xpath("//span[@class='mpn-value']")
print(mpn.text) 

此外,对于每一页,按钮的数量和名称都有所不同。因此,如果有任何通用的解决方案,我可以扩展到所有页面,所有按钮,这将是非常感谢。谢谢


Tags: 代码fromimportsizebydriver页面element
1条回答
网友
1楼 · 发布于 2024-07-01 07:55:40

欢迎来到SO

你离正确的解决方案只差一小步!特别是find_element_by_xpath()函数返回单个元素,但是类似的函数find_elements_by_xpath()(注意复数形式)返回一个iterable列表,您可以使用它来实现for循环

下面是MWE以及您提供的示例页面

from selenium import webdriver
import time

driver = webdriver.Firefox() # initiate the driver

driver.get("https://www.1800cpap.com/resmed-airfit-n30-nasal-cpap-mask-with-headgear")

time.sleep(2) # sleep for a couple seconds to ensure correct upload

mpn = [] # initiate an empty results' list
for button in driver.find_elements_by_xpath("//label[@data-label='label-custcol3']"):
    button.click()    
    mpn.append(driver.find_element_by_xpath("//span[@class='mpn-value']").text)

print(mpn) # print results

相关问题 更多 >

    热门问题