[英]Get all value and items from drop down list using selenium
I am trying to extract values from dropdown using python selenium. I am getting the text but not getting the values with xpath. Code I used is我正在尝试使用 python selenium 从下拉列表中提取值。我正在获取文本,但没有使用 xpath 获取值。我使用的代码是
from selenium.common.exceptions import WebDriverException
from selenium import webdriver
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.3"
}
options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
URL = ['https://www.classicalmusicartists.com/cma/artists.aspx']
for url in URL:
try:
driver = webdriver.Chrome(executable_path = '/home/ubuntu/selenium_drivers/chromedriver', options = options)
driver.get(url)
driver.implicitly_wait(2)
datas = driver.find_element("xpath",'//select[@id="ctl00_cphMainContent_lstCategory"]')
d= Select(datas)
for opt in d.options:
print(opt.text)
driver.quit()
except WebDriverException:
driver.quit()
So what you should do is:所以你应该做的是:
ds = [d.text for d in datas.find_elements('tag name','option')]
you were using the improper tag locator.您使用了不正确的标签定位器。 Options are tags not names, the 'name=' attribute (similar to class names) inside a tag element.
选项是标签而不是名称,标签元素内的 'name=' 属性(类似于 class 名称)。 Secondly you were looking for a singular item and then iterating over that element (as it was a single item there isn't any support for iteration over it to retrieve the text element) so had to make it
.find_elements()
to find all such matches.其次,您正在寻找一个单一的项目,然后遍历该元素(因为它是一个单一的项目,所以不支持对其进行迭代以检索文本元素)所以必须让它
.find_elements()
找到所有这样的火柴。
And to get the values you could do:并获得你可以做的价值:
dv = [d.get_attribute('value') for d in datas.find_elements('tag name','option')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.