我是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
循环上方,它将创建文件。
为什么会这样?
答案 0 :(得分:2)
在这里,它不会创建文件的唯一原因是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')
答案 1 :(得分:0)
您没有处理正确的异常,也没有以二进制模式编写字符串。不会创建文件的唯一原因是在while循环期间执行停止。