[英]How to define configparser in python 3
我正在開發一個將登錄該站點並評論用戶生成的內容的項目。
我使用 selenium、chrome 驅動程序和 python 3. 所有憑據用戶名、密碼和 chromedriver 位置都在單獨的 config.ini 文件中配置。
這是 python 腳本:
#!/usr/bin/python
import os
import time
import getpass
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from configparser import ConfigParser
# Reading configuration file
config = configparser.ConfigParser()
config.sections()
parser = ConfigParser()
parser.read('config.ini')
parameters = {}
for pairs in parser.sections(): # Parse the configuration file
for name, value in parser.items(pairs):
parameters[name] = value
# Automating your browser
chromedriver = parameters["path"]
os.environ["webdriver.chrome.driver"] = chromedriver
#Uncomment this block if you don't want images to load(makes the procss a little bit faster)
'''
chromeOptions = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images":2}
chromeOptions.add_experimental_option("prefs",prefs)
browser = webdriver.Chrome(chromedriver, chrome_options=chromeOptions)
'''
browser = webdriver.Chrome(chromedriver)
browser.set_window_size(1120, 550)
browser.get("http://www.website.com") # website home page
time.sleep(3)
# Logging into website
form = browser.find_element_by_class_name('regular_login')
email = form.find_element_by_name("email")
password = form.find_element_by_name("password")
email.send_keys(parameters["email_id"])
try:
pass_word = parameters["pass_word"]
except:
pass_word = getpass.getpass() # If you want to enter password on terminal
password.send_keys(pass_word)
password.send_keys(Keys.RETURN)
time.sleep(2)
# Fetching answers page of t6he user
answers_url = "https://www.website.com/" + parameters["username"] + "/answers"
browser.get(answers_url)
#commenting answers one by one from top to bottom
counter=0
while True:
try:
elem=browser.find_element_by_xpath("//*[@action_click='enter']")
counter=counter+1
elem.click()
time.sleep(4)
except:
break
print (str(counter) +" answers commented..")
我不斷得到,
config = configparser.ConfigParser()
NameError: name 'configparser' is not defined
拜托,任何人都可以回答我如何定義配置。
發生此錯誤是因為您尚未實際導入configparser
。 您已從 configparser
導入了某些內容,但實際上尚未導入configparser
本身。
有兩種解決方案。
1)您可以通過導入模塊來定義它。 import configparser
2)或者按照從錯誤開始向下3行的方式進行操作,並使用config = ConfigParser()
如果您正在使用configparser
其他部分,那么我建議您導入整個模塊並使用選項1。如果您僅使用ConfigParser
那么我將使用選項2。
你有config = configparser.ConfigParser()
你應該有config = ConfigParser()
您不需要指定 configparser 因為您是從它導入的,所以您只需使用您正在導入的 class 即ConfigParser
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.