Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Formatting, f-strings #6660

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 2 additions & 3 deletions instapy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
# __variables__ with double-quoted values will be available in setup.py
__version__ = "0.6.16"

from .file_manager import get_workspace, set_workspace
from .instapy import InstaPy
from .util import smart_run
from .settings import Settings
from .file_manager import set_workspace
from .file_manager import get_workspace
from .util import smart_run
40 changes: 22 additions & 18 deletions instapy/browser.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,34 @@
# import built-in & third-party modules
import os
import zipfile
import shutil

import zipfile
from os.path import sep

from selenium import webdriver

# import exceptions
from selenium.common.exceptions import (
UnexpectedAlertPresentException,
WebDriverException,
)
from selenium.webdriver import Remote
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options as Firefox_Options
from selenium.webdriver import Remote
from webdriverdownloader import GeckoDriverDownloader

# import InstaPy modules
from .util import interruption_handler
from .util import highlight_print
from .util import emergency_exit
from .util import get_current_url
from .util import check_authorization
from .util import web_address_navigator
from .file_manager import use_assets
from .settings import Settings
from .time_util import sleep

# import exceptions
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import UnexpectedAlertPresentException
# import InstaPy modules
from .util import (
check_authorization,
emergency_exit,
get_current_url,
highlight_print,
interruption_handler,
web_address_navigator,
)


def get_geckodriver():
Expand Down Expand Up @@ -116,7 +121,7 @@ def set_selenium_local_session(
firefox_profile.update_preferences()

# geckodriver log in specific user logfolder
geckodriver_log = "{}geckodriver.log".format(logfolder)
geckodriver_log = f"{logfolder}geckodriver.log"

# prefer user path before downloaded one
driver_path = geckodriver_path or get_geckodriver()
Expand Down Expand Up @@ -145,8 +150,7 @@ def set_selenium_local_session(
browser.set_window_size(414, 896)
except UnexpectedAlertPresentException as exc:
logger.exception(
"Unexpected alert on resizing web browser!\n\t"
"{}".format(str(exc).encode("utf-8"))
f"Unexpected alert on resizing web browser!\n\t{str(exc).encode('utf-8')}"
)
close_browser(browser, False, logger)
return browser, "Unexpected alert on browser resize"
Expand Down Expand Up @@ -277,7 +281,7 @@ class custom_browser(Remote):

def find_element_by_xpath(self, *args, **kwargs):
"""example usage of hooking into built in functions"""
rv = super(custom_browser, self).find_element_by_xpath(*args, **kwargs)
rv = super().find_element_by_xpath(*args, **kwargs)
return rv

def wait_for_valid_connection(self, username, logger):
Expand All @@ -298,7 +302,7 @@ def wait_for_valid_authorization(self, username, logger):
# stuck on invalid auth
auth_method = "activity counts"
counter = 0
while True and counter < 10:
while counter < 10:
login_state = check_authorization(self, username, auth_method, logger)
if login_state is False:
logger.warning("not logged in")
Expand Down
6 changes: 2 additions & 4 deletions instapy/clarifai_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,7 @@ def check_image(
clarifai_tags.extend(results)

logger.info(
"source_link {} got predicted result(s):\n{}".format(
source_link, clarifai_tags
)
f"source_link {source_link} got predicted result(s):\n{clarifai_tags}"
)

# Will not comment on an image if any of the tags in
Expand All @@ -98,7 +96,7 @@ def check_image(
return True, [], clarifai_tags

except Exception as err:
logger.error("Image check error: {}".format(err))
logger.error(f"Image check error: {err}")


def given_tags_in_result(search_tags, clarifai_tags, full_match=False):
Expand Down
16 changes: 6 additions & 10 deletions instapy/comment_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def comment_image(browser, username, comments, blacklist, logger, logfolder):
except WebDriverException as ex:
logger.error(ex)

logger.info("--> Commented: {}".format(rand_comment.encode("utf-8")))
logger.info(f"--> Commented: {rand_comment.encode('utf-8')}")
Event().commented(username)

# get the post-comment delay time to sleep
Expand All @@ -157,12 +157,12 @@ def verify_commenting(browser, maximum, minimum, logger):

commenting_state, msg = is_commenting_enabled(browser, logger)
if commenting_state is not True:
disapproval_reason = "--> Not commenting! {}".format(msg)
disapproval_reason = f"--> Not commenting! {msg}"
return False, disapproval_reason

comments_count, msg = get_comments_count(browser, logger)
if comments_count is None:
disapproval_reason = "--> Not commenting! {}".format(msg)
disapproval_reason = f"--> Not commenting! {msg}"
return False, disapproval_reason

if maximum is not None and comments_count > maximum:
Expand Down Expand Up @@ -325,9 +325,7 @@ def get_comments_on_post(
random.shuffle(comment_data)

logger.info(
"Grabbed only {} usable comment(s) from this post...".format(
len(comment_data)
)
f"Grabbed only {len(comment_data)} usable comment(s) from this post..."
)

return comment_data
Expand Down Expand Up @@ -370,9 +368,7 @@ def verify_commented_image(browser, link, owner, logger):

if commenter and commenter == owner:
message = (
"--> The post has already been commented on before: '{}'".format(
comment
)
f"--> The post has already been commented on before: '{comment}'"
)
return True, message

Expand Down Expand Up @@ -464,7 +460,7 @@ def process_comments(
)

# Return to the target uset page
user_link = "https://www.instagram.com/{}/".format(user_name)
user_link = f"https://www.instagram.com/{user_name}/"
web_address_navigator(browser, user_link)

return comment_state
18 changes: 8 additions & 10 deletions instapy/commenters_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def extract_post_info(browser, logger):
user_commented = (
comm.find_element(By.TAG_NAME, "a").get_attribute("href").split("/")
)
logger.info("Found commenter: {}".format(user_commented[3]))
logger.info(f"Found commenter: {user_commented[3]}")
user_commented_list.append(user_commented[3])

except Exception as e:
Expand Down Expand Up @@ -220,7 +220,7 @@ def extract_information(browser, username, daysold, max_pic, logger):
)
click_element(browser, close_overlay)

logger.info("Date of this picture was: {}".format(date_of_pic))
logger.info(f"Date of this picture was: {date_of_pic}")

if date_of_pic < pastdate:
logger.info("Finished scrolling, too old photos...")
Expand Down Expand Up @@ -252,9 +252,9 @@ def extract_information(browser, username, daysold, max_pic, logger):
if max_pic <= 0:
break
max_pic -= 1
logger.info("{} of max {} --- {} to go.".format(counter, len(links4), max_pic))
logger.info(f"{counter} of max {len(links4)} --- {max_pic} to go.")
counter = counter + 1
logger.info("Scrapping link: {}".format(link))
logger.info(f"Scrapping link: {link}")

try:
web_address_navigator(browser, link)
Expand All @@ -264,7 +264,7 @@ def extract_information(browser, username, daysold, max_pic, logger):
# stop if date older than daysago
pastdate = datetime.now() - timedelta(days=daysold)
date_of_pic = datetime.strptime(pic_date_time, "%Y-%m-%dT%H:%M:%S.%fZ")
logger.info("Date of pic: {}".format(date_of_pic))
logger.info(f"Date of pic: {date_of_pic}")

if date_of_pic > pastdate:
logger.info("Recent pic, continue...")
Expand Down Expand Up @@ -316,9 +316,7 @@ def users_liked(browser, photo_url, amount=100, logger=None):
sleep(2)
except NoSuchElementException:
logger.info(
"Could not get information from post: {} nothing to return".format(
photo_url
)
f"Could not get information from post: {photo_url} nothing to return"
)

return photo_likers
Expand Down Expand Up @@ -431,7 +429,7 @@ def likers_from_photo(browser, amount=20, logger=None):
return user_list

except Exception as exc:
logger.warning("Some problem occurred! \n\t{}".format(str(exc).encode("utf-8")))
logger.warning(f"Some problem occurred! \n\t{str(exc).encode('utf-8')}")
return []


Expand All @@ -441,7 +439,7 @@ def get_photo_urls_from_profile(
# try:
# input can be both username or user profile url
username = username_url_to_username(username)
logger.info("Getting likers from user: {}".format(username))
logger.info(f"Getting likers from user: {username}")

web_address_navigator(browser, "https://www.instagram.com/" + username + "/")
sleep(1)
Expand Down
18 changes: 8 additions & 10 deletions instapy/file_manager.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
""" A file management utility """

import os
from os.path import expanduser
from os.path import exists as path_exists
from os.path import expanduser
from os.path import sep as native_slash
from platform import python_version

from .util import highlight_print
from .settings import Settings
from .settings import localize_path
from .settings import WORKSPACE
from .exceptions import InstaPyError
from .settings import WORKSPACE, Settings, localize_path
from .util import highlight_print


def use_workspace():
Expand All @@ -22,7 +20,7 @@ def use_workspace():

def use_assets():
"""Get asset folder"""
assets_path = "{}{}assets".format(use_workspace(), native_slash)
assets_path = f"{use_workspace()}{native_slash}assets"
validate_path(assets_path)
return assets_path

Expand All @@ -35,9 +33,9 @@ def get_workspace():

else:
home_dir = get_home_path()
workspace = "{}/{}".format(home_dir, WORKSPACE["name"])
workspace = f"{home_dir}/{WORKSPACE['name']}"

message = 'Workspace in use: "{}"'.format(workspace)
message = f'Workspace in use: "{workspace}"'
highlight_print(
Settings.profile["name"], message, "workspace", "info", Settings.logger
)
Expand All @@ -56,7 +54,7 @@ def set_workspace(path=None):
if workspace_is_new:
update_workspace(path)
update_locations()
message = 'Custom workspace set: "{}" :]'.format(path)
message = f'Custom workspace set: "{path}" :]'
highlight_print(
Settings.profile["name"],
message,
Expand Down Expand Up @@ -171,7 +169,7 @@ def verify_workspace_name(path):

if default_workspace_name not in custom_workspace_name:
if default_workspace_name.lower() not in custom_workspace_name.lower():
path += "/{}".format(default_workspace_name)
path += f"/{default_workspace_name}"
else:
nicer_name = custom_workspace_name.lower().replace(
default_workspace_name.lower(), default_workspace_name
Expand Down
4 changes: 2 additions & 2 deletions instapy/follow_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def get_following_status(
read_xpath(get_following_status.__name__, "follow_span_XP_following"),
)
return "Following", follow_button
except:
except Exception:
return "UNAVAILABLE", None
follow_button = explicit_wait(
browser, "VOEL", [follow_button_XP, "XPath"], logger, 7, False
Expand Down Expand Up @@ -115,5 +115,5 @@ def verify_username_by_id(browser, username, person, person_id, logger, logfolde
return person_new

# check who call this def, since will receive a None value
logger.info("User '{}' doesn't exist in local records".format(person))
logger.info(f"User '{person}' doesn't exist in local records")
return None