Python 带函数错误的循环:TypeError:';datetime.datetime';对象不可调用
我的Python程序有问题。我有以下错误:Python 带函数错误的循环:TypeError:';datetime.datetime';对象不可调用,python,Python,我的Python程序有问题。我有以下错误: TypeError: 'datetime.datetime' object is not callable 这是我的节目: from selenium.webdriver.support import expected_conditions as EC from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support
TypeError: 'datetime.datetime' object is not callable
这是我的节目:
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from tkinter import filedialog
from selenium import webdriver
from bs4 import BeautifulSoup
from datetime import datetime
from lxml import etree
import tkinter as tk
import calendar
import fnmatch
import requests
import locale
import string
import shutil
import time
import glob
import re
import os
# Choix du dossier contenant les fichiers HTML
root = tk.Tk()
root.withdraw()
file_path = filedialog.askdirectory()
print(file_path + "/*.HTML")
if len(glob.glob(file_path + "/*.HTML")) == 0:
print("Aucuns fichiers HTML au sein du dossier sélectionné.")
date_entry = input('Entrer une date au format YYYY-MM-DD')
last_date = datetime.strptime(date_entry, "%Y-%m-%d")
else:
print("Il y a des fichiers")
last_date = last_date(file_path)
#driver = webdriver.Chrome(ChromeDriverManager().install())
options = webdriver.ChromeOptions()
options.add_argument("--no-startup-window")
options.add_argument("download.default_directory=/Users/####/Desktop/")
# Webdriver Chrome
driver = webdriver.Chrome('/usr/local/bin/chromedriver')
# Unice connexion vers europresse
driver.get("#####")
# On rentre les identifiants
username = driver.find_element_by_id("username")
password = driver.find_element_by_id("password")
# On renseigne les identifiants et on envoie
username.send_keys("#####")
password.send_keys("######")
driver.find_element_by_name("submit").click()
# Recherche avancée mode classique
driver.get("###########")
now = datetime.now()
while now > last_date :
# Mots clés
keywords = driver.find_element_by_id("Keywords")
keywords.send_keys('TEXT= ("price"| "consumer price index" |"CPI" |"deflation"| "disinflation" |"inflation" |"inflationary") & "United States"| LEAD= ("price"| "consumer price index" |"CPI" |"deflation"| "disinflation" |"inflation" |"inflationary")| TIT_HEAD= ("price"| "consumer price index" |"CPI" |"deflation"| "disinflation" |"inflation" |"inflationary") & "United States"')
# Listes déroulantes des critères
time.sleep(5)
critere = driver.find_elements_by_xpath("//div[@id='ui-id-2']//img[@class='node']")
time.sleep(5)
# Déroule la provenance
critere[1].click()
# Déroule les types
critere[2].click()
# Déroule les langues
critere[3].click()
# Sélection des types
time.sleep(3)
critere = driver.find_elements_by_xpath("//div[@class='nom-sources']//img[@class='node']")
critere[9].click()
time.sleep(2)
driver.find_element(By.XPATH, '//span[text()="Journaux"]').click()
driver.find_element(By.XPATH, '//span[text()="Magazines et revues"]').click()
driver.find_element(By.XPATH, '//span[text()="Presse Web référencée"]').click()
driver.find_element(By.XPATH, '//span[text()="Presse Web"]').click()
# Opérateur AND
driver.find_element_by_id("and").click()
# Sélection de la langue
critere = driver.find_elements_by_xpath("//div[@class='nom-sources']//img[@class='node']")
driver.find_element(By.XPATH, '//span[text()="Anglais"]').click()
# Sélection de la provenance
critere = driver.find_elements_by_xpath("//div[@class='nom-sources']//img[@class='node']")
# Sélection Amérique du Nord
critere[2].click()
time.sleep(2)
driver.find_element(By.XPATH, '//span[text()="États-Unis"]').click()
# Date de l'article du plus ancien au plus récent
date_periode = Select(driver.find_element_by_id('DateFilter_DateRange'))
date_periode.select_by_value('10')
d = last_date.strftime("%Y-%m-%d")
# Spécifie la date de début
driver.execute_script("document.getElementById('dateStart').value='" + d + "'")
# Lancer la recherche
driver.find_element_by_class_name("button-search-orange").click()
# Temps de pause scroll
SCROLL_PAUSE_TIME = 3
SCROLL_START = 15
SCROLL_END = 50
time.sleep(SCROLL_START)
# Date de l'article du plus ancien au plus récent
select = Select(driver.find_element_by_id('ddlSort'))
select.select_by_value('9')
time.sleep(10)
# Récupération de l'élément à scroller
elscr = driver.find_element_by_id('resultList')
time.sleep(10)
# Récupération du nombres d'articles chargés
nbre_article = int(driver.find_element_by_id("documentLoadedCount").text)
# Boucle pour le scroll jusqu'à 1000 articles
while nbre_article < 100 :
time.sleep(SCROLL_PAUSE_TIME)
driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', elscr)
nbre_article = int(driver.find_element_by_id("documentLoadedCount").text)
# Selectionner tout les articles
driver.find_element_by_class_name("custom-checkbox").click()
time.sleep(SCROLL_PAUSE_TIME)
# Clique sur le bouton save
driver.find_element_by_id('save').click()
time.sleep(SCROLL_PAUSE_TIME)
# Clique sur le bouton
driver.find_element_by_id('okBtn').click()
time.sleep(5)
# Switch vers le iframe
iframe = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to.frame(iframe)
# Clique sur le bouton de téléchargement
time.sleep(10)
driver.find_element_by_tag_name("a").click()
time.sleep(20)
last_date = last_date(file_path)
当我在程序开始时调用函数
last_date()
时,没有问题,我从html文件中得到了正确的日期。但是问题发生在我的程序结束时,我调用函数last\u date()
。。。我真的想从datetime import datetime重命名,换言之,不做任何更改,我真的不知道为什么日期不可调用,所以它一开始就可以工作。感谢提前(我知道代码有点长) 正如Azro所说,问题一定是您使用与函数相同的名称命名变量(last\u date=last\u date(文件路径)
)
在循环的第一次迭代中,last_date指的是函数,因此last_date()
调用函数。
当您执行last\u date=last\u date(文件路径)
时,last\u date
不再引用您的函数,而是引用您的对象good\u date
或者,日期对象不可调用(它不是函数),这就是为什么出现类型错误:“datetime.datetime”对象不可调用的原因不要将变量命名为与方法相同的名称,请参见last\u date=last\u date(file\u path)
不要这样做请使用完整的错误回溯更新您的问题。我不想通过搜索所有这些代码来找到错误。就是这样,它现在工作得很好!这是一个粗心的错误。。。非常感谢:)@阿兰库松没问题。如果你的问题解决了,你可以将我的答案标记为已接受(这样你的问题就会变成绿色,人们知道问题已经解决)。你只需要在答案的选票下面勾选绿色的复选标记。
def last_date(html_source):
# Récupération des chemins des fichiers html
html_files = []
for root, dirs, files in os.walk(html_source):
for file in files:
if file.endswith(".HTML"):
html_files.append(os.path.join(root, file))
# Récupération du chemin du dernier fichier html téléchargé
latest_file = max(html_files, key=os.path.getctime)
# Récupération du nom du dernier fichier html téléchargé
base = os.path.basename(latest_file)
name_file = os.path.splitext(base)[0]
# Récupération du nom du dossier
folder_name = os.path.dirname(latest_file)
# Ouvre le dernier fichier HTML
html = open(latest_file, "r", encoding='utf8')
content = html.read()
soup = BeautifulSoup(content, "lxml")
date_articles = []
articles = soup.findAll("article")
for a in articles:
date_f = []
article_date = a.find("span", {"class", "DocHeader"})
date_f = get_date(article_date.text)
date_articles.append(date_f)
# Récupère la date du max et min des articles
maxi = (max(date_articles))
mini = (min(date_articles))
print(mini)
print(type(mini))
new_name = "/" + mini.strftime("%B %d %Y") + " - " + maxi.strftime("%B %d %Y") + '.HTML'
new_name_file = folder_name + "/" + mini.strftime("%B %d %Y") + " - " + maxi.strftime("%B %d %Y") + '.HTML'
new_folder_file = "Users/####/Desktop/##### ### ####" + new_name
# Renomme le fichier
os.rename(latest_file, new_name_file)
print(mini)
return mini
def get_date(date_string):
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
date_article = re.findall(r'\b[^\W0-9_]+ \d{1,2}\b, [0-9]+', date_string)
date_f = date_article[0]
good_date = datetime.strptime(date_f, '%B %d, %Y')
return good_date