在我编写的一个脚本中,有一段代码如下所示:
try:
prize = row.find_element(By.XPATH, './div[contains(@class, "divCell")][3]').text
except:
prize = ''
try:
field = row.find_element(By.XPATH, './div[contains(@class, "divCell")][4]').text
except:
field = ''
try:
country = row.find_element(By.XPATH, './div[contains(@class, "divCell")][5]/span[1]/a').get_attribute('title')
except:
country = ''
try:
city = row.find_element(By.XPATH, './div[contains(@class, "divCell")][5]/span[2]').text
except:
city = ''
try:
winner = row.find_element(By.XPATH, './div[contains(@class, "divCell")][6]/span[2]/span').get_attribute('data-highlightingclass')
except:
winner = ''
try:
runnerup = row.find_element(By.XPATH, './div[contains(@class, "divCell")][7]/span[2]/span').get_attribute('data-highlightingclass')
except:
runnerup = ''
我是Python新手,想知道是否有其他更简洁的方法来实现这一点?你知道吗
前言:请提供Minimal, Complete, and Verifiable example帮助我们。你知道吗
我假设你正在使用硒。你知道吗
你有不同的选择。你知道吗
一句话就可以把他们全部抓住
如果所有元素都是必需的,那么您最好使用一个更大的try-catch:
(请注意,Selenium文档recommends to使用方法
WebDriver.find_element_by_xpath
,而不是直接使用WebDriver.find_element
)封装
(由@vks推荐)
您可以环绕异常并返回
None
,而不是使用可以直接引发异常的方法:然后这样使用:
编辑:也可以使用lambdas。你知道吗
完全封装
您甚至可以通过使用lambdas显式地声明要提取的内容来实现精简:
以及:
相关问题 更多 >
编程相关推荐