gpt4 book ai didi

python - 为什么这不创建文件?

转载 作者:行者123 更新时间:2023-12-01 01:48:10 25 4
gpt4 key购买 nike

我是 Python、Selenium 等方面的新手。我只是想知道为什么在这种情况下,当我运行脚本时,没有创建并写入 test.txt

import scrapy
from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = Firefox(executable_path='C:\webdriver\geckodriver.exe')
driver.get('https://www.indiegogo.com/explore/wellness?project_type=campaign&project_timing=all&tags=&sort=trending')

show_more = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//div[@class="text-center"]/a'))
)

while True:
try:
show_more.click()
except TimeoutException:
break

filename = 'test.txt'
with open(filename, 'wb') as datafile:
datafile.write('asdfsdf')

print(driver.page_source)
driver.close()

问题在于 break 似乎打破了整个脚本,而不仅仅是 while 循环。换句话说,如果我将 with open 移到 while 循环上方,它就会创建该文件。

为什么会这样?!

最佳答案

这里,它无法创建文件的唯一原因是 show_more.click() 调用抛出了 TimeoutException 之外的其他内容。在这种情况下,该功能/程序将被完全跳过。

您可以捕获所有异常,并尝试打印要改进的异常(捕获所有异常并不是很好,有时您必须停止处理)

while True:
try:
show_more.click()
except (TimeoutException,Exception) as e:
print(str(e)) # with that information you're able to refine Exception into something more accurate
break

filename = 'test.txt'
with open(filename, 'w') as datafile:
datafile.write('asdfsdf')

关于python - 为什么这不创建文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51017384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com