click()不起作用,而是在调用一个不需要的函数



我正在使用selenium与网站进行交互。我以twitter为例。

这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
r = 0
def loadPage():
driver = webdriver.Firefox()
driver.set_window_size(800, 800)
#url = "about:blank"
url = "http://www.twitter.com/login"
driver.get(url)
login(driver)
def login(driver):
print("login was called")
name = "session[username_or_email]"
global r
try:
elem = driver.find_element_by_name(name)
elem.clear()
elem.send_keys("@someaccount")
elem.send_keys(Keys.TAB)
actions = ActionChains(driver)
actions.send_keys('password')
actions.send_keys(Keys.RETURN)
actions.perform()
r=0
retweet(driver)
except:
driver.implicitly_wait(3)
r+=1
if r <= 5: #only try this 5 times
print(r)
login(driver)
else:
print("Could not find element " + name)
#driver.close()
def retweet(driver):
g = 'g'
print(driver.current_url)
icon = driver.find_elements_by_tag_name(g)
icon.click()
loadPage()

当函数retweet((被调用时,第43行的icon.click((调用函数login((。(预期行为是执行单击,而不是调用函数login((。(

使用";icon.send_keys(keys.RURN(";在线43处表现出相同的行为。

程序输出:

login was called
1
login was called
https://twitter.com/login
1
login was called
https://twitter.com/login
1
login was called
2
login was called
3
login was called
4
login was called
5
login was called
Could not find element session[username_or_email]

登录函数被一次又一次调用的原因,因为它在icon = driver.find_elements_by_tag_name(g)行找到了NoSuchElementException。一旦出现异常,它将在except块下执行代码。这只是按照上面的代码调用登录方法。

现在,为什么即使页面上有过多的标签可用,也会出现NoSuchElementException?为了回答这个问题,如果你在检查模式下看到你的页面,所有的<g>标签都在<svg>标签内。为了识别<svg>标签,我们需要使用xpath的name方法。所以,如果你将使用下面它不会抛出异常:

def retweet(driver):
xpathLink = "//*[name()='svg']//*[name()='g']"
print(driver.current_url)
icon = driver.find_element_by_xpath(xpathLink )
icon.click()

但是,仍然你不会点击转发链接,因为上面xpath会在twitter页面上找到任何链接图标。所以,如果你想点击转发链接,只需要使用下面的xpath。

xpathRetweet = //div[@data-testid='retweet']//*[name()='svg']//*[name()='g']

注意:以上内容将始终单击页面上的第一个转发链接。若要单击页面上的所有内容。您需要使用find_elements来获取所有转发链接的列表,并逐一单击它们。

相关内容

最新更新