Questions tagged [python-3.x]

DO NOT UTILIZE UNLESS YOUR INQUIRY IS FOR SOLELY PYTHON 3 PURPOSES. Please ensure to consistently employ this in tandem with the customary [python] label.

Adjusting the size of browser windows to half of the screen with the help of Selenium

Is there a method available to resize two windows to half of the screen size with Selenium? If not, any alternative suggestions are welcome. I am currently working with Python and Chromium, but willing to consider other options. ...

What is the process for removing an element from a PyListObject using the `pop`

If I have a PyListObject and need to add a PyObject, I would typically use the PyList_Append API as detailed in the List Objects C-API. However, in my scenario, I require removing an element from the same PyListObject (similar to my_list.pop() in Python). ...

Calculate the total number of unique prime numbers in a given array using Python

Consider the following scenario - You are provided with an array A containing N integers. Let's say G represents the product of all elements in A. The task is to determine the count of distinct prime divisors of G. Example - Input : A = 1, 2, 3, 4 Output ...

"Utilize URL parameters to specify a date range when working with Django Rest

In my JSON structure, I have data entries with timestamps and names: [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-20 03:26:53", "name": "ab" }, { "date": "2017-12- ...

Experiencing an AssertionError: The result must be None, a string, bytes, or StreamResponse. Having trouble finding a resolution to this issue?

I have implemented a post API that reads JSON content from a file. When a request is made to the API, the device_id is provided. Using this device_id, I fetch entities related to it. Here's the code snippet: class EntityBasedOnDeviceId(HomeAssistantVi ...

Is it possible to merge a dictionary with text file writing and then retrieve it as a dictionary once again?

I am making requests to a link and receiving JSON files as response. I am storing this data in a text file, but when I try to read it back, I want to interpret it as a dictionary. How can I achieve this? def url_sequence(limit=5): for i in range(limit ...

Can all exceptions for requests be consistently captured? (And more broadly, for a module)

I'm dealing with some code that involves making a requests.get() call, which could potentially fail in different ways. My goal is to catch any exceptions related to requests, without necessarily needing to know the specific reason for the failure. I ...

Extract a Key from a JSON Dictionary using Python

I've recently started working on a script as part of my practice routine. The purpose of the script is to take user input and then store it inside a Json file. Here's how the code looks: import json command = int(input("Do You Want To Add, Or Re ...

What is the process for exclusively installing pip on Python 3.7?

Having Python 3.7, I am looking to install pip on my system. However, when I try the command: sudo apt install python3-pip The installation seems to download Python version 3.6 along with pip for that version. Is there a way to only install pip for Pytho ...

Error: The variable "tree" has not been declared

Hello, I am a Python newcomer and I'm currently following a tutorial. However, I encountered the following error: NameError: name 'tree' is not defined. The goal of my program is to classify fruits as either apples or oranges based on t ...

Issue with dropdown menu in selenium is that it is unable to switch to the second option

Currently, I am in the process of web scraping on a specific page . When Selenium initiates the initial loading of the page, I encounter a requirement to select both the state and city. To address this, I attempted using the .click method. select_state = d ...

Python deal with JSON floating with leading zeros

Is there a way to format floats with trailing zeros using the Python (3.5) json standard library? import json to_be_serialized = {'something': 0.020} print(json.dumps(to_be_serialized)) {"something": 0.02} # expected output: {"something": 0.020 ...

Exploring network traffic using Selenium and PhantomJS

Exploring ways to capture website traffic while browsing using Selenium with python has led me to a dilemma - since most of the traffic is encrypted (https), using a proxy may not be effective. One idea I came up with is running phantomJS with selenium an ...

Guide on retrieving location link with the help of Selenium WebDriver in Python

I tried using the following code snippet in Python with Selenium WebDriver to extract the "Locations" link, but I was only able to retrieve the text "Locations" and not the actual link. Can anyone provide assistance with this? Link to be extracted from: ...

What is the best method to override a class attribute that is two levels deep?

When it comes to overriding and inheritance, I've noticed that things are not working as expected in my code. Let me break down the scenario for you: I have three classes - Card, Treasure, and Copper. Copper inherits from Treasure, and Treasure inherits fr ...

What are the signs that indicate a webpage is offline or unresponsive?

I have developed a Python code that checks the availability of web pages stored in a tuple by browsing them using Selenium. The objective is to regularly check if these pages are online and responding. Here is a snippet of the code: from selenium import w ...

Python ElementTree: Fetching sibling tag values from XML

I've been attempting to extract the value of the ci-name element where the sibling RandomAttribute's value is IMPORTANT. I am new to Python and I am using Python's built-in ElementTree for this task. Below is a snippet of the XML data: < ...

Ways to retrieve the values from a collection of objects inside a Model using Python

In my system, there are two modes available: User and Friends. This represents a one-to-many relationship. My goal is to retrieve the values in the following manner: record = User.query.filter_by(id=7).first() Below are the methods and properties associ ...

Generate a list of JSON strings using a collection of Pydantic objects

I have been working on extracting a list of JSON strings from a collection of Pydantic objects. My current approach involves the following code snippet: raw_books = [json.dumps(x.dict()) for x in batch.books] While this method functions properly, it tends ...

Aggregate and Group Data in Pandas while retaining all columns

I'm dealing with a Dataframe structured like this: -------------------------------------------------------------------- |TradeGroup | Fund Name | Contribution | From | To | | A | Fund_1 | 0.20 | 2013-01-01 | 2013-01 ...

Using Python with Selenium, automate the process of clicking on each list item within

Hey there! I recently implemented the code below, and it worked perfectly. However, I'm now trying to figure out how to make it click on all the li items within a ul that have an empty class attribute. Any ideas on how to do this using Xpath? Xpath: ('// ...

Pytest is not able to locate any elements on the webpage, yet the same elements can be easily found using the console

When using CSS or XPath in the console (F12), I am able to locate the element on the page. $$("span.menu-item[data-vars-category-name='Most Popular']") However, when trying to find the same elements with Selenium (pytest) using: driver.find_el ...

Encountered an issue while attempting to access the JSON file. Error message: [json.decoder.JSONDecodeError: Anticipating property

Recently, I have been facing some difficulties while attempting to open a json file in Python 3.8 using the json library. My attempts so far have not been successful. Here is a minimal working example (MWE) of my code: with open(pbit_path + file_name, 'r' ...

Grab the code segment from one file and replace the corresponding segment in another file

I am facing an issue with copying codes from one file and pasting them into another file between specific lines. Here is the scenario: I have two files named test.sv_old and test.sv. My goal is to extract code from the test.sv_old file and insert it into ...

struggling with setting up a Python script to automate logging into several email accounts

Here is my code where I am attempting to create a function that includes a list to log into each email account one at a time. The issue I am facing is that it is trying to loop through the entire list instead of logging into one email at a time. How can I ...

Combining JSON data within a MySQL column efficiently with the power of SQLAlchemy

Is there a way to consolidate JSON data that is spread out over multiple rows in a MySQL column using the Python SQLAlchemy library? I tried using json_merge_preserve but encountered difficulties applying it to an entire column. This was the code snippet ...

A guide on storing user inputs in a config or JSON file for future retrieval

My function involves retrieving user input to correct column names in a dataset that do not match the master dataset. For instance, if the master dataset has columns X, Y, Z but the child dataset uses A, B, C. I prompt the user to input the correct names ...

Troubles encountered when trying to save an Excel.Writer document to a different directory

A timed backup system is being developed for an Excel document using Python, since there will be multiple users accessing it. The goal is to alter the file path away from the local directory. Below is the code snippet; import pandas as pd import datetime ...

Would you be able to assist me in automating the clicking of the Postcode Checker Search button using selenium

Struggling with my Selenium tutorial in Python as I can't get the postcode search button to click. Using: Python v3.9 Chrome v87 The URL for practice is: This is the code snippet I'm currently working with: # Selenium Tutorial #1 from selenium import ...

I am looking for the C# counterpart of hexdigest function used in Python 3.2. Can anyone help me with

Currently, I am in the process of transitioning a Python 3.2 program to C#. Within the Python program, there is a line of code that returns a string object with double the length, consisting solely of hexadecimal digits. The specific snippet from the Pyt ...

I am curious about how to input a new location into a GPS system

Can anyone advise on how to add noise to a GPS point (latitude and longitude) using a Gaussian distribution with a radius of 10m in Python? ...

Creating a MySQL database from a CSV file: A step-by-step guide

I am looking to streamline the database creation process by utilizing a CSV file that contains 160 columns and 15 rows of data. Manually assigning names for each column is proving to be quite challenging due to the large number of columns. I have managed t ...

Guide on closing Shopee pop-up windows using Selenium

I'm having trouble closing the popup on the website using selenium. Please see the image below. I attempted the following code, but encountered errors: NoNoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selecto ...

The decryption process using GnuPG is successful on Windows but encounters issues on Linux

I am currently utilizing the python-gnupg library to decrypt a file using a self-generated key. Strangely, the following code executes successfully on Windows: import gnupg import os key_data = '''-----BEGIN PGP PRIVATE KEY BLOCK----- <key data here> ...

using selenium in python to specifically target a class

Is there a way to specify which element with the class name "table_dark_green" I would like to use when using the selenium module for Python 3 to retrieve information from a website? The issue is that there are multiple elements on the site with this cla ...

Unable to retrieve profile names from duplicate URLs with requests

Having an issue with logging into Facebook using selenium and transferring cookies to the requests module in order to collect profile names from specific URLs. The profile names on these URLs are static but require authentication. While my script successf ...

Leveraging permutations to discover the subsequent largest numeral

Develop a function that accepts a positive integer as input and generates the next largest number possible by rearranging its digits. The solution for this task involved the following approach: Here is the logic applied: Create a script to find all perm ...

Can you find a solution using the GUI interface?

Hello, I am currently working on a program to confirm pregnancy using hormone levels (HCG as an integer parameter in a dictionary). However, when testing the GUI, I encountered the following error: "TypeError: string indices must be integers" while checkin ...

Display chosen choices in Selenium using Python

I need help with a code that should list the selected options from the page, but nothing is being printed. Here's the HTML code snippet: <select class="chosen-select" id="tag_opts" name="tag_opts[]" tabindex="-1" multiple="true" data-placeholder="Selec ...

Can you elaborate on the purpose and functionality of the continue statement

Could someone provide an explanation for the continue statement? I've been struggling to comprehend it, despite my best efforts. The Python docs contain a sample program that I can't seem to figure out. for num in range(2, 10): if num % 2 == 0: ...

Python2 has the site-packages folder, while Python3 does not have it

When I am logged in as the root user, I noticed the following: root@5d6f29f1d4e9:/usr/local/lib/python2.7# ls -a . .. dist-packages site-packages root@5d6f29f1d4e9:/usr/local/lib/python3.6# ls -a . .. dist-packages Upon running this command: find / ...

"Enhancing visual appeal: Tidying up the backdrop in a stack

I have a simple animation featuring a basic line plot using ax.plot(...). I decided to tweak it so that it now displays a stackplot instead of the line plot (see code snippet below). The issue is that the plot doesn't seem to refresh the background with e ...

What is the best way to eliminate the specific element containing our desired word from the webpage data extracted through selenium?

After scraping 6 elements from a website using the Selenium find_element(By.XPATH) module, I stored these elements in a list. I then converted these elements into text and searched on Google. However, due to the ever-changing nature of the elements, somet ...

Struggling to extract dynamic table information from the Human Microbiom Project (HMP) with Python's Beautiful Soup and Selenium

Currently, I am trying to extract the dynamic table data from the 'File UUID' column on the HMP website using Python (Beautiful Soup and Selenium). However, despite successfully extracting other columns, I am facing difficulty in retrieving the specific co ...

Exploring the Beauty of Selenium and Python by Navigating Links

On a webpage, there are multiple links displayed randomly. The code I've written is set to open the first link in a new tab and perform a function. However, I'm unsure how to handle this if there are more than one link. Is there a way to iterate through th ...

Is there a way for me to direct a call to a staticmethod using a decorator?

Python Version Requirement: Python 3.7 or newer I am currently developing a solution to encode/decode a model using a versioned json/yaml schema. My goal is to find a streamlined way to implement this without resorting to long if-elif-else chains that che ...

What could be causing my program to unexpectedly halt while running an infinite loop?

It seems like it should be simple, but I'm currently following a tutorial that includes this code snippet: n=0 a=1 while a>0: n=n+1 a=(1.0+2.0**(-n))-1.0 print (n) When I tried to run this code, it keeps stopping at n=53. What could be cau ...

List using letters instead of numerals

Can Python provide a method similar to enumerate() but with letters instead of numbers? For instance x = ['block', 'cheese'] for letter, word in enumerate(x): print((letter, word)) This code would result in ('A', ' ...

Python - Deleting an integer from a list effectively

# Initialize list "time" with various time values time = [15, 27, 32, 36.5, 38.5, 40.5, 41.5, 42, 43.5, 45.5, 47.5, 52.5] # Remove the first value from the list time[0] = [] # Display time time [[], 27, 32, 36.5, 38.5, 40.5, 41.5, 42, 43.5, 45.5, 47.5, ...

The synchronization between Python datetime and system time is not functioning properly

Can someone guide me on how to synchronize datetime with the system time in real-time? I want my code to display a different hour, minute, and second each time it runs. Here's the code I'm currently using: from datetime import datetime import os from time ...

The exception thrown by Runtime.callFunctionOn was due to an error in LavaMoat - the property "Proxy" of globalThis is not accessible in scuttling mode

As I work on developing a Next.js app, I encountered some challenges when trying to run tests with selenium-webdriver. My webapp utilizes authentication with Metamask wallets, and the issue arises when attempting to import a wallet into a test window using ...

Guide to Making a Next Button in Tkinter for Easy Frame Switching

In my tkinter quiz program, each question has its own frame. After the user selects the correct answer from a radiobutton list, a window pops up allowing them to navigate between questions. Here's an example: https://i.stack.imgur.com/Hij8g.png Instead of ...

Python 3 - troubleshooting an issue with if statement not accurately recognizing a specific string

I am currently working through the book "Learn Python The Hard Way". In the example provided below, an input string is being compared to specific values. After running the code, it becomes apparent that any input containing the specified word plus additio ...

Entering a date in a disabled datepicker using Selenium

I am encountering an issue while trying to input my own chosen date as the datepicker is disabled. Whenever I click on the datepicker, it prompts me to select a specific date and even for changing the month, multiple clicks are required. This has left me f ...

Error: Cannot find module 'selenium.webdriver.common'

Recently, I started learning Python. To practice what I have learned so far, I decided to create a new Python project using PyCharm. However, when I tried running my simple program, I encountered the following error. "C:\D drive\Workspace\P ...

Having trouble closing the popup with the Selenium driver, the main problem seems to be the element not being found

When attempting to close a popup using selenium's find element method with xpath, it fails to detect the popup. After trying methods like time.sleep(10) and driver.find_element(By.XPATH, "XPATH").close(), the issue persists. I've also experimented with us ...

The Python tkmacosx is throwing an error related to the "systemWindowBackgroundColor" property

Currently, I am facing a challenge with changing the foreground color of a button on my Mac running Big Sur. I have attempted to resolve this by installing tkmacosx, but it seems there may be an issue with the package. Whenever I run the code below or att ...

Develop a script that filters the load information and stock market data contained in target.csv for specific subsets

Create a program that extracts specific data subsets from the target.csv file related to stock market information. Load the contents of target.csv into a variable named 'target'. From the 'target' data, create a new dataframe called &ap ...

How can I use XPATH and Python Selenium to select the text node that is outside of an <a> element?

Check out the following link: Within this section of code: //*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td, there is a piece of text Mottled Boar slain (10) //*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td/a This part contains only: Mo ...

dividing binary numbers by 2 and 8

My task is to determine if certain binary numbers are divisible by 2 or 8 and then report the total count. If the last digit of a binary number is 0, it's divisible by 2, and if the last three digits are all 0, it's divisible by 8. twos = 0 eigh ...

The I2C slave remains unresponsive until a new script is invoked at regular intervals

After successfully programming an ATtiny1627 as an I2C slave to respond to the read_i2c_block_data() function, a challenge arose when trying to have a Raspberry Pi 4 act as the I2C master. The goal was for the Pi to read the data from the ATtiny every 500m ...

Element pairs optimized prefix tree

Below is a representation of my nested list: lists = [['a', 'b', 'c', 'd'], ['a', 'b', 'd', 'e'], ['a', 'b', 'd', 'f' ...

Find a particular item by referencing a different element

I am attempting to save an element into a string variable, however, in order to locate the desired element I require another element that meets specific conditions. The reason for not directly accessing the intended element is due to the presence of multip ...

Updating a text file with fresh data in Python using the OS library

Referencing the code provided by user "qmorgan" on Stack Overflow here. Essentially, I am attempting to generate a new text file if it doesn't already exist. If the file does exist, then overwrite its contents. The problem I'm encountering is that using 'a ...

Hiding Chrome Web Driver Icon in Python-Selenium

UPDATED FOR BETTER PERFORMANCE Aim: Operate chrome web driver in the background without revealing an app icon in the dock or application bar. Please note that while I can run chrome headless, I've not yet found a way to prevent the chrome icon from appear ...

dictionary comprehension not functioning properly

Let's create a dictionary that stores the frequency of each character in a specific string str1 = "peter piper picked a peck of pickled peppers" freq = {} freq2 = {} for c in str1: freq[c] = freq.get(c, 0) + 1 freq2 = ...

Looking to extract text from an h3 tag class with Python and selenium?

I am currently facing a challenge when it comes to extracting text from a specific webpage: https://i.stack.imgur.com/YNo0Y.png My attempts with browser.find_element_by_class_name("W6bZuc.YMllz").text have been unsuccessful. I also tried browser.find_e ...

Tips for grabbing the following element locator path with Selenium?

I am working on a piece of code to download a CSV file. Here is the code snippet: chromedriver = "/usr/lib/chromium-browser/chromedriver" driver = webdriver.Chrome(chromedriver) driver.get('https://www.aemo.com.au/Electricity/National-Electricity-Mar ...

Using an integer variable to iterate a string within a function in Python

Being a complete novice, I've tried delving into several related topics but I just can't seem to grasp it. My goal is to write a function that will iterate through the string s exactly "n" times. s="hello" n=2 When I use s[::n] it works fine ...

Transferring a list of decimal numbers from a Python server to another using Flask and the requests library

I am working on a project that involves periodically sending an Array of doubles from a Python service to another. Despite being a newcomer to Python, I have delved into topics like Flask and requests. Below is a basic code example that I put together jus ...

Error encountered while attempting a simple input operation

Hey there! So, I'm pretty new to python and I have a question about a simple script I'm working on: print('What is your name?') person = input("Enter name: ") print("Hello ", person) But every time I run it, I get this error message: NameError: name 'Bob ...

Ways to eliminate attributes from dataclasses

I am working with a dataclass that looks like this: @dataclass class Bla: arg1: Optional[int] = None arg2: Optional[str] = None arg3: Optional[Dict[str, str]] = None My objective is to achieve the following behavior: >>> bla = Bla(a ...

Tips on setting up virtualenv for Python 3 on a Mac

I have multiple versions of Python installed on my Mac and I want to set python3 as the default version while also using virtualenv and virtualenvwrapper. To achieve this, I created an alias in my ~/.zshrc alias python='python3' I also added the followi ...

Tips for dynamically extracting the activated tags from a webpage with Python and Selenium

I have been working on a website where I have implemented the Google Analytics code through Google Tag Manager. The site consists of numerous pages, and I am interested in ensuring that the Google Analytics code fires correctly on all pages. One method is ...

Looking for ways to use Python to access Google Chrome Extensions like Session Buddy?

I am looking to utilize Python to retrieve all currently open URLs from Chrome using Session Buddy. With Session Buddy, you can save all open URLs in a .csv file by completing a few simple steps (essentially clicking buttons), which will then download the ...