Python get followers usernames via python selenium - selenium-webdriver

I try to get follower list from an acocunt but even if there are 211 followers, follower who at the end of following box has xpath : ('/html/body/div[2]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div/div[3]/div/div/div[208]/div[2]/div[1]/div/div/div/a/span/div')
therefore I've when loop goes to above 208. Can you help me? Thank you so much. This is my first entry on stackoverflow.
**After login and click into profile that I want to investigate :
**
`following_panel = driver.find_element_by_xpath('/html/body/div[2]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div/div[3]')
time.sleep(5)
last_ht, ht = 0, 1
while last_ht != ht:
last_ht = ht
time.sleep(4)
# scroll down and retrun the height of scroll
ht = driver.execute_script("""
arguments[0].scrollTo(0, arguments[0].scrollHeight);
return arguments[0].scrollHeight; """, following_panel)
list_of_followings = []
i=1
while i<209:
list_of_followings.append(driver.find_element_by_xpath(f'/html/body/div[2]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div/div[3]/div/div/div[{i}]/div[2]/div[1]/div/div/div/a/span/div').text)
i+=1
print(list_of_followings)
print("****************")`

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Wait for the followers to be present on the page
following_panel = driver.find_element_by_xpath('/html/body/div[2]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div/div[3]')
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, './/div[#class="PZuss"]')))
# Extract the follower names
followers = following_panel.find_elements_by_xpath('.//div[#class="PZuss"]')
list_of_followings = []
for follower in followers:
name = follower.find_element_by_xpath('.//a/span/div').text
list_of_followings.append(name)
print(list_of_followings)
print("****************")
This code will wait for up to 10 seconds for the followers to be present on the page before trying to find them.

Related

Getting more than 1 post from a sub at a time

reddit = praw.Reddit(client_id='xyz',
client_secret='xyz',
user_agent='xyz',check_for_async=False)
#bot.command(aliases=['memes'])
async def meme(ctx):
memes_submissions = reddit.subreddit('dankmemes').new()
post_to_pick = random.randint(1, 10)
for i in range(0, post_to_pick):
submission = next(x for x in memes_submissions if not x.stickied)
embed = discord.Embed(title= f"Meme-" ,color=0xFF00FF)
embed.set_image(url=submission.url)
'''embed.set_thumbnail(url=ctx.author.avatar_url)'''
embed.set_footer(text='requested by: \n{0}'.format(ctx.author),icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
i wrote this down to extract 1 meme at a time from reddit sub "dankmemes"
i was wondering if theres a way through which i can ask for top 5 memes or get more than just one meme?
any suggestions will be of a lot of help. tysm!
You can get top posts from a subreddit by using the subreddit.top member.
max_top = 5
subreddit = reddit.subreddit('sample_subreddit_with_good_memes')
top = subreddit.top(limit=max_top)
The built-in random library has a function named choices() which gives you a list with multiple randomly selected choices. So you can basically get the top 100 posts and then get 10 random memes from the list.

Gatling - print current time before execution of scenario and pass that value to next scenario

I am executing 2 consecutive scenarios, I have a requirement where I need to record current time before start of 1st scenario and then pass that time value to next scenario. Can someone please suggest how this can be implemented. Please check below my code
def fileUpload() = foreach("${datasetIdList}","datasetId"){
println("File Upload Start Time::::"+Calendar.getInstance().getTime+" for datasetId ::: ${datasetId}")
exec(http("file upload").post("/datasets/${datasetId}/uploadFile")
.formUpload("File","./src/test/resources/data/Scan_good.csv")
.header("content-type","multipart/form-data")
.check(status is 200).check(status.saveAs("uploadStatus")))
.exec(session => {
if(session("uploadStatus").as[Int] == 200)
counter +=1
session
})
}
def getDataSetId() = foreach("${datasetIdList}","datasetId"){
exec(http("get datasetId")
.get("/datasets/${datasetId}")
.header("content-type","application/json")
.check(status is 200)
)
I need to record upload start time for each iteration of datasetIdList and pass that value to next scenario and print that value for each datasetId. can someone please suggest how this can be implemented
You may try using before section
package load
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class TransferTimeSimulation extends Simulation {
var beforeScn1Start: Long = 0L
before {
println("Simulation is about to start!")
beforeScn1Start = System.currentTimeMillis()
}
after {
println("Simulation is finished!")
}
val scn1 = scenario("Scenario 1").exec(
http("get google")
.get("http://google.com")
.check(status.is(200))
)
val scn2 = scenario("Scenario 2")
.exec { session =>
println("beforeScn1Start = " + beforeScn1Start)
session
}
setUp(
scn1.inject(atOnceUsers(1))
.andThen(scn2.inject(atOnceUsers(1)))
)
.protocols(http)
.maxDuration(10)
.assertions(
forAll.failedRequests.count.is(0),
)
}
For more flexibilty you may also consider using lazy val initialization
https://www.baeldung.com/scala/lazy-val

How do you create a while true loop while still keeping a tkinter page open?

I am trying to create a tkinter page that shows the time and it should be constantly updated. I have tried:
from tkinter.font import *
import time
def SetTime():
global time_date
time_date = time.strftime("%H:%M")
InfoTime.set(time_date)
Main = Tk()
Main.geometry("1600x1200")
Main.title("Time")
FontStyle = Font(family = "Times New Roman", size = 48)
InfoTime = StringVar()
TitleText = Label(Main,textvariable = InfoTime,font = FontStyle).pack()
while True:
SetTime()
However, running the
While True: line and running
SetTime()
constantly is for some reason preventing the tkinter page (Main) from opening. This has been a problem for a lot of my tkinter projects.
Please note, I am running python 3.7.2 in IDLE.
Thanks.
This should do it:
from tkinter import *
from tkinter.font import *
import time
Main = Tk()
Main.geometry("1600x1200")
Main.title("Time")
FontStyle = Font(family = "Times New Roman", size = 48)
TitleText = Label(Main, font = FontStyle)
TitleText.pack()
time_date1 = ''
def SetTime():
global time_date1
global TitleText
# Gets current time
time_date2 = time.strftime("%H:%M")
# If time has changed, update it
if time_date2 != time_date1:
time_date1 = time_date2
TitleText.config(text=time_date2)
# Repeats function every 200 milliseconds
TitleText.after(200, SetTime)
SetTime()
Main.mainloop()
The comments pretty much explain everything. I also cleaned up and reformatted your code to make it look nicer.

Is there a way to use/get the value from a current entry window

I'm trying to get the variable that's entered in an entry widget on the Return key pressed event, but struggling a bit. What I have tried has always produced a blank result.
This code may look messy and hap-hazard, but it's only going to be a template that I'll be using on a current project!
I've tried that many things to get it to work, I can't remember what I have tried!
from collections import OrderedDict
try:
import tkinter as tk
except:
import Tkinter as tk
root = tk.Tk()
labelLIST = OrderedDict([
('Temp ID', 'tempID'),
('PO Number', "poNumber"),
('Reference', "reference"),
('Cut/Sample Date', "csDate"),
('Cut Number', "cut")
])
i = 0
e_loops = len(labelLIST)
print (e_loops)
def bval1(event=None):
for i in range(e_loops):
print (entries[i].get())
entries[0].delete(0, tk.END)
entries[0].insert(0, 'DISABLED')
entries[0].configure(state='disabled')
def bval2():
entries[0].configure(state='normal')
for i in range(e_loops):
entries[i].delete(0, tk.END)
entries[0].focus()
def onClick(event):
ent = event.widget # event.widget is the widget that called the event
print(ent.cget("text")) # Print the text for the selected button
event.widget.tk_focusNext().focus()
def enterEV(event):
# print(entries[].get())
event.widget.tk_focusNext().focus()
entries = []
for key, value in labelLIST.items():
label = tk.Label(root, text=key)
label.grid(row=i, column=0, sticky="ew", padx=1, pady=1)
entry = tk.Entry(root, width=10)
entry.grid(row=i, column=1, sticky="ew", padx=5, pady=5)
if value == "cut":
entry.bind('<Return>', bval1)
else:
# entry.bind('<Return>', enterEV)
entry.bind('<Return>', onClick)
entries.append(entry)
i = i+1
button = tk.Button(root, text="Submit", command=bval1)
button.grid(row=0, column=2, columnspan=9, sticky="ew")
button = tk.Button(root, text="Clear", command=bval2)
button.grid(row=1, column=2, columnspan=9, sticky="ew")
entries[0].focus()
tk.mainloop()
When enter/return is pressed, I want the value that is the entry box to be printed to terminal via the onClick event. But the output is always empty.
def onClick(event):
ent = event.widget # event.widget is the widget that called the event
print(ent.cget("text")) # Print the text for the selected button
event.widget.tk_focusNext().focus()
You don't use the text attribute to get the value in an Entry widget. Using cget("text") returns the value for the textvariable attribute. Since you haven't set that attribute, it will always be the empty string.
Instead, you need to call the get method:
print(ent.get())

How to update a combo box with a list of items

I am trying to update the list of items in one combobox2 depending on the item selected in another - combobox1.
For example, if the user selects a file.mp3 in combobox1 then combobox2 will display a list of audio extension (.aac, .wav, .wma). However, if the user selects a file.flv from combobox1, combobox2 will display a list of video extensions (.mpg, mp4, .avi, .mov).
I initially thought I could accomplish this with if statements. The initial selection works, but there after, if you continue to choose different files, the combobox2 is not updated. I tried using an Event, but it didn't work.
Below if a very stripped-down version of the code so that you can get the gist:
import wx
import os
import sys
import time
from wx.lib.delayedresult import startWorker
class udCombo(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'd-Converter', size=(500, 310))
panel = wx.Panel(self, wx.ID_ANY)#Creates a panel over the widget
toolbar = self.CreateToolBar()
toolbar.Realize()
font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD)
font2 = wx.Font(7, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
directory = wx.StaticText(panel, -1, 'Path to media files: c:\\ffmpeg\\bin', (300, 13))
directory.SetFont(font2)
convertfile = wx.StaticText(panel, -1, 'File:', (270, 53))
convertfile.SetFont(font)
convertfile2 = wx.StaticText(panel, -1, 'Format:', (245, 83))
#Select Media
os.chdir("c:\\ffmpeg\\bin")
wrkdir = os.getcwd()
filelist = os.listdir(wrkdir)
self.formats1 = []
for filename in filelist:
(head, filename) = os.path.split(filename)
if filename.endswith(".avi") or filename.endswith(".mp4") or filename.endswith(".flv") or filename.endswith(".mov") or filename.endswith(".mpeg4") or filename.endswith(".mpeg") or filename.endswith(".mpg2") or filename.endswith(".wav") or filename.endswith(".mp3"):
self.formats1.append(filename)
self.format_combo1=wx.ComboBox(panel, size=(140, -1),value='Select Media', choices=self.formats1, style=wx.CB_DROPDOWN, pos=(300,50))
self.Bind(wx.EVT_COMBOBOX, self.fileFormats, self.format_combo1)
self.format_combo2=wx.ComboBox(panel, size=(100, -1),pos=(300,81))
self.Bind(wx.EVT_COMBOBOX, self.fileFormats, self.format_combo2)
def fileFormats(self, e):
myFormats = {'audio': ('.wav', '.wma', '.mp3'), 'video': ('.mpg', '.mp4', '.mpeg')}
bad_file = ['Media not supported']
myFile = self.format_combo1.GetValue()
f_exten = [x for x in myFormats['audio'] or myFormats['video'] if myFile.endswith(x)]
if f_exten[0] in myFormats['audio']:
self.format_combo2.SetItems(myFormats['audio'])
elif f_exten[0] in myFormats['video']:
self.format_combo2.SetItems(myFormats['video'])
else:
self.format_combo2.SetItems(bad_file)
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = udCombo()
frame.SetSizeHints(500,310,500,310)
frame.Show()
app.MainLoop()
Traceback error:
Traceback (most recent call last):
File "C:\Users\GVRSQA004\Desktop\udCombo.py", line 86, in fileFormats
if f_exten[0] in myFormats['audio']:
IndexError: list index out of range
Use a dictionary to hold the two lists. Then when the user clicks something in the first widget, you can call the second combobox's SetItems(myDict[selection]) method or something along those lines. The error message is because you're trying to do something with a CommandEvent that it doesn't support. They don't have an "rfind" attribute, for example.
EDIT: The new code the OP posted doesn't work because it's only running the list comprehension against the first half of the OR statement. It never runs against the "video" portion, so it returns an empty list if the user chooses anything with a video format extension. It WILL work if you select an audio selection.
Personally, I would recommend creating a video extension list and an audio list. That would be easier to understand in the future should you need to fix it later.

Resources