硒的例外:如何继续脚本?



我的代码一直遇到问题。虽然我终于能够打开网页,单击按钮并下载 excel 文件,但我遇到了一个错误:找不到这样的元素。

我有一个 URL 列表,Selenium 可以很好地浏览列表,直到它遇到具有不同配置的 url 并且找不到"元素"。我只想让python跳过该网址并转到下一个网址。将来我可以手动返回到"损坏的URL"。

这是我的代码:

with open('C:/Users/ovtch/PyScript/source.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
urlList.append(row['URL'])
driver = webdriver.Chrome(executable_path='chromedriver.exe')

def downloadCSV():
count=1
for url in urlList:
driver.get(url)
# Page Scraping Prepare
time.sleep(1)
driver.find_element_by_xpath('my path').click()
time.sleep(1)
driver.find_element_by_xpath('my path').click()
count+=1
"""Show starting time"""
print("Start project time")
print(datetime.datetime.now().time())
downloadCSV()
"""Show end time"""
print("End project time")
print("Success")
time.sleep(8)
#driver.quit()

试试这个,将你的 find_element_by_* 方法包装在一个异常块中并相应地处理异常

from selenium.common.exceptions import NoSuchElementException
def downloadCSV():
count=1
for url in urlList:
try:
driver.get(url)
# Page Scraping Prepare
time.sleep(1)
driver.find_element_by_xpath('my path').click()
time.sleep(1)
driver.find_element_by_xpath('my path').click()
count+=1
except NoSuchElementException:
pass # or handle the error

您可以使用 try/catch 并忽略错误并继续循环:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#your code....
for url in urlList:
try:
driver.get(url)
# Page Scraping Prepare
# Wait until your button is clickable and click
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "my path"))).click()
except:
continue

最新更新