Python Selenium - 计算列表框中的项目数

时间:2017-12-19 23:23:27

标签: python selenium listbox

我正在尝试计算网页上列表框中的项目数,然后从此列表框中选择多个项目。我可以选择好的项目,我正在努力找出如何计算列表框中的项目。

见代码:

from selenium import webdriver
from selenium.webdriver.support.ui import Select

......

accountListBox = Select(driver.find_element_by_id("ctl00_MainContent_accountItemsListBox"))
accountListBox.select_by_index(0)

print(len(accountListBox))

我尝试使用len()导致错误“TypeError:类型为'Select'的对象没有len()”。

我也试过了accountListBox.size(),并从第3行中删除了“选择”,这也是行不通的。

对此非常陌生,所以非常感谢您的反馈。

谢谢!

3 个答案:

答案 0 :(得分:1)

根据docs,可以通过override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.swiped = false if let touch = touches.first { lastPoint = touch.location(in: self.view) print(lastPoint) } } func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions((tempImageView.image?.size)!, false, scale) let context = UIGraphicsGetCurrentContext() tempImageView.image?.draw(in: CGRect(origin: CGPoint.zero, size: (tempImageView.image?.size)!)) //let context = UIGraphicsGetCurrentContext() print("context size = \(context)") print("fromPoint = \(fromPoint), toPoint = \(toPoint)") context?.move(to: CGPoint(x: fromPoint.x, y:fromPoint.y)) context?.addLine(to: CGPoint(x: toPoint.x, y:toPoint.y)) context?.setBlendMode(CGBlendMode.normal) context?.setLineCap(CGLineCap.round) context?.setLineWidth(5) context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor) context?.strokePath() tempImageView.image = UIGraphicsGetImageFromCurrentImageContext() self.newImage = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext()!) UIGraphicsEndImageContext() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { swiped = true if let touch = touches.first { let currentPoint = touch.location(in: self.view) drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint) lastPoint = currentPoint print(lastPoint) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if !swiped { drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint) } } 来获取选择元素列表的选项。在您的特定情况下,这将是select.options,您需要在 上调用accountListBox.options,而不是在len()实例本身上调用:

Select

或者,如果您只想打印当前所选选项的列表:

print(len(accountListBox.options))

答案 1 :(得分:0)

您应该使用find_elements为每个列表框的项目使用一些公共选择器来查找所有这些项目,将找到的元素存储到变量中,并使用本机python的库来计算它们。

答案 2 :(得分:0)

我经常使用Selenium和Beautiful Soup。 Beautiful Soup是一个用于解析HTML和XML文档的Python包。

使用Beautiful Soup,您可以通过以下方式获取列表框中的项目数:

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.PhantomJS() # or webdriver.Firefox()
driver.get('http://some-website.com/some-page/')

html = driver.page_source.encode('utf-8')
b = BeautifulSoup(html, 'lxml')
items = b.find_all('p', attrs={'id':'ctl00_MainContent_accountItemsListBox'})
print(len(items))

我假设您要查找的DOM元素是段落(p标记),但您可以将其替换为您需要查找的任何元素。