Par*_*eog 3 python selenium automation
不确定标题应该是什么,请随意编辑。我是Selenium的新手,只是在玩弄它。我尝试在我最喜欢的网站之一(10fastfingers.com)上进行实验,我经常用它来练习打字。我尝试使用最新版本的 Selenium 和 Python(3.5.*) 来自动输入。自动化可以工作,但速度真的很慢。
这是我的示例脚本,我不知道为什么它变慢。如果有人能在这里帮助我那就太好了。我原以为脚本会超过 100 WPM,但实际上只达到了37 WPM
问题是,只有两行单词可见,因此,它不会一次获取所有单词,当您继续输入单词时,单词会不断出现。所以,我不能一次接受所有单词,并将其存储在一个列表中,然后稍后循环它们。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://10fastfingers.com/typing-test/english")
input = driver.find_element_by_id("inputfield")
for i in range(300):
word = driver.find_element_by_class_name("highlight")
word = word.text
print("Typing word ", word)
input.send_keys(word)
input.send_keys(Keys.SPACE)
Run Code Online (Sandbox Code Playgroud)
更新
我尝试获取之前的所有单词,而不是按照 @ alecxecfind_element_*的建议在循环内使用。为此,我必须使用BeautifulSoup来解析 HTML,因为它是字符串格式,并且我无法使用它的任何函数。以下脚本将打字速度提高到138 WPM。但是,我注意到前 20 秒的打字速度非常快,然后速度开始逐渐下降。请随时在您的计算机上试用该脚本,并让我知道该脚本在您的系统上实现的测试(WPM)结果。也许这也取决于系统配置。我不知道。这是内存问题吗?或者代码问题?知道如何解决这个问题吗?find_element_*
修改代码
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
driver = webdriver.Firefox()
driver.get("http://10fastfingers.com/typing-test/english")
input = driver.find_element_by_id("inputfield")
script = "return document.getElementById('row1').innerHTML"
all_words= driver.execute_script(script)
soup = BeautifulSoup(all_words, 'html.parser')
words = soup.find_all('span')
for word in words:
text = word.text
input.send_keys(text + Keys.SPACE)
Run Code Online (Sandbox Code Playgroud)
更新2
我重新启动了系统,并关闭了所有其他应用程序,脚本像魔术一样运行,在计时器达到 60 秒之前它就输入了所有 361 个可用单词,结果是361 WPM。因此,这取决于可用的 RAM。
每个.find_element_*、.text等.send_keys()调用都是涉及 HTTP 请求/响应(请参阅JSON 有线协议)处理的 WebDriver 命令。您可以通过获取word循环之前的值来显着减少发送的 WebDriver 命令数量:
word = driver.find_element_by_class_name("highlight").text
for i in range(300):
print("Typing word ", word)
input.send_keys(word + Keys.SPACE)
Run Code Online (Sandbox Code Playgroud)
我也加入了send_keys()一个通话。
请注意,有一种更好的方法来处理这个特定的用例。所有的单词实际上都存在于 HTML 中,您只需要获取它们即可。.text只会返回可见文本,请get_attribute("textContent")改为使用:
input_elm = driver.find_element_by_id("inputfield")
words_to_type = [word.get_attribute("textContent") + Keys.SPACE
for word in driver.find_elements_by_css_selector("#row1 > span")]
for word in words_to_type:
input_elm.send_keys(word)
Run Code Online (Sandbox Code Playgroud)
或者说,那又怎么样?使用动作链- 预先准备动作然后执行(在我的机器上每分钟 360 个字):
from selenium.webdriver import ActionChains
input_elm = driver.find_element_by_id("inputfield")
actions = ActionChains(driver)
actions = actions.move_to_element(input_elm).click()
for word in driver.find_elements_by_css_selector("#row1 > span"):
actions = actions.send_keys(word.get_attribute("textContent") + Keys.SPACE)
actions.perform()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2252 次 |
| 最近记录: |