Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么不创建一个文件?_Python_Selenium - Fatal编程技术网

Python 为什么不创建一个文件?

Python 为什么不创建一个文件?,python,selenium,Python,Selenium,我不熟悉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

我不熟悉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
循环。换句话说,如果我在
while
循环上方使用open移动
,它确实会创建文件


为什么会这样

您没有处理正确的异常,也没有以二进制模式写入字符串。它不会创建文件的唯一原因是执行在while循环期间停止。

在这里,它不会创建文件的唯一原因是
显示更多。click()
调用抛出的不是
TimeoutException
的内容。在这种情况下,功能/程序被完全跳过

您可以捕获所有异常,并尝试打印您将获得的异常以对其进行细化(捕获所有异常不是很好,有时您必须停止处理)


确保您正在签入文件的正确位置。还要确保datafile.write行是通过在该行的上方和下方打印某些内容来执行的。@Anthony它肯定不会中断while循环。不是更多。可能发生的情况是,在
show\u more中出现异常。单击()
(不是超时),它将退出函数。尝试捕获
异常
(所有异常)@Anthony我回滚了你的帖子。不要使用解决方案进行编辑。编辑只是为了澄清。我不在乎它写了什么,只在乎它是否创建了文件。当我将带open的
移动到循环上方时,它会奇怪地工作是的,我不知道。上面的代码修复了该问题,但需要在知道异常的确切性质后进行更改。
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')