【问题标题】:Obtaining data on clicking multiple radio buttons in a page using selenium in python在python中使用selenium获取单击页面中多个单选按钮的数据
【发布时间】:2020-06-30 19:36:56
【问题描述】:

我有一个页面,上面有 3 个单选按钮。我希望我的代码连续单击这些按钮中的每一个,并在单击它们时显示一个值(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) 

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

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    欢迎来到 SO!

    您离正确的解决方案只有一小步!特别是,find_element_by_xpath() 函数返回单个元素,但类似的函数 find_elements_by_xpath()(注意复数)返回一个可迭代列表,您可以使用它来实现 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
    

    【讨论】:

    • 嗨,你到底是什么意思?循环遍历不同的 url 很简单:你创建一个 url 列表,然后循环遍历它,每次 driver.get() 中的值都会改变。
    • P. S. 注意 webdriver 需要一些时间来上传:在两个页面之间使用 time.sleep() 1 或 2 秒
    猜你喜欢
    • 2020-02-11
    • 1970-01-01
    • 2014-02-14
    • 2020-11-28
    • 2017-09-12
    • 2021-03-16
    • 1970-01-01
    • 2014-09-21
    • 2019-03-17
    相关资源
    最近更新 更多