If Xpath doesn't exist, play mp3 - Python - python

I want to set up an alarm, so when a website changes, it will play a song on my computer.
I'm not sure how to set up the conditional statement for this. Below is what I've written, but obviously it isn't correct. If the element on the website exists, I want to end but if it doesnt exist, (the website has changed) I want the mp3 to play as an alarm.
if driver.find_element(By.XPATH, "/html/body/div[1]/div[2]/h1"):
else:
webbrowser.open(r"C:\Users\Julian Layton\Desktop\Andalusia\I Remember.mp3")
I also want this script run every 2 minutes. How can I do this? (Using VS Code)

You can do something like this:
if not driver.find_elements(By.XPATH, "/html/body/div[1]/div[2]/h1"):
webbrowser.open(r"C:\Users\Julian Layton\Desktop\Andalusia\I Remember.mp3")
find_elements method returns a list of web elements.
In case no elements found it returns an empty list interpreted as False by Python. This will involve your command.
In order to run this every 2 minutes you can put this in loop with 2 minutes delay
while True:
if not driver.find_elements(By.XPATH, "/html/body/div[1]/div[2]/h1"):
webbrowser.open(r"C:\Users\Julian Layton\Desktop\Andalusia\I Remember.mp3")
break
else:
time.sleep(120)
here I added a 2 minutes sleep between iterations and a break to stop this in case of calling the music file. Not sure what exactly logic you are looking for, this seems to me to be matching your question.

Related

Loading imaging interposition with clicking element. Fluent waiting time not working

This is my first question so apologice in advance.
I am trying to automate loading an online form, which you have to do one case at a time.
Some inputs request information from the server and freezes the webpage with a loading spining gif, afterwards some fields are autocompleted.
I am having issues at the end of the first entry where I need to ADD the current info in order to reset everything and start the process again.
The exception ElementClickInterceptedException raises inspite of using fluent waiting. I have tried several ways using Xpath or script executor but it throws the same error
any thoughts?
send ID 1 and 2
driver.find_element(By.ID,'bodyContent_PRD_EFE_txtNroIDPrestador').send_keys(ID)
driver.find_element(By.ID,'bodyContent_PRD_PRE_txtNroIDPrestador').send_keys(ID2)
for i in prestaciones.index: #this is a pd.DataFrame wherei store the data to fill the form
afi=WebDriverWait(driver,5).until(
EC.element_to_be_clickable((By.ID,'bodyContent_PID_txtNroIDAfiliado'))) #store the input element
if afi.get_attribute('value')=='': #check if its empty and fill it
afi.send_keys(str(prestaciones['n af'][i]))
else:
driver.find_element(By.ID,'bodyContent_PID_btnNroIDAfiliado_Clean').click()
afi.send_keys(str(prestaciones['n af'][i]))
#select something from a scroll down list
prog_int=Select(driver.find_element(By.ID,'bodyContent_PV1Internacion_selTipoAdmision'))
prog_int.select_by_value('P')
#fill more input
diag=driver.find_element(By.ID,'bodyContent_DG1_txtNroIDDiagnostico').get_attribute('value')
if diag=='':
driver.find_element(By.ID,'bodyContent_DG1_txtNroIDDiagnostico').send_keys('I10')
#select more inputs
tip_prac=Select(driver.find_element(By.ID,'bodyContent_PRE_selSistemaCodificacion'))
tip_prac.select_by_value('1')
#Codigo de prestacion
prest= driver.find_element(By.ID,'bodyContent_PRE_txtCodigoPrestacion')
if prest=='': #deal with the data in the input for next round of loading
prest.send_keys(str(prestaciones['codigo'][i]))
else:
prest.clear()
prest.send_keys(str(prestaciones['codigo'][i]))
#select amount of items
cant=driver.find_element(By.ID,'bodyContent_PRE_txtCantidadTratamientoSolicitados').get_attribute('value')
if cant == '':
driver.find_element(By.ID,'bodyContent_PRE_txtCantidadTratamientoSolicitados').send_keys('1')
#HERE IS THE DEAL. some fields make a loading gift appears and caches the click. I have tried several ways and it throws that exception or the time out one with the execute script
aceptar=WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "bodyContent_PRE_btnTablaPrestaciones_Add")))
aceptar.click()

How do I enter a list of text from a txt file to a variable in python?

activation = driver.find_element(By.XPATH, '//*[#id="__layout"]/div/aside/div/div[1]/section[1]/div[1]/div/div/form/div[2]/div/span')
code = driver.find_element(By.XPATH, '//*[#id="__layout"]/div/aside/div/div[1]/section[1]/div[1]/div/div/form/div/input')
list = open("C:\Users\infin\Desktop\List.txt", "r")
I want to enter a list of code from List.txt into code as long as activation is true and create a loop depending on how many elements the list has
For example, if the list has 5 codes, I want to see that if activation is true or not. If it is true, it will timeout for 120 seconds (I can do this part)
Then after 120 seconds, it will enter the codes from the list.txt to code
I am still learning python and I'm trying out different stuffs and learning new words in python
I don't know if I understand your problem but if you have codes in separated lines then you can do
all_codes = open("C:\\Users\\infin\\Desktop\\List.txt", "r").read().split('\n')
Better use \\ in path because \ is used for special chars like \n (new line), \t (tab), etc. - even in path - and single \ can make problem. OR use prefix r for raw string.
all_codes = open(r"C:\Users\infin\Desktop\List.txt", "r").read().split('\n')
And next you need for-loop to get single code, send it to input and check result.
from selenium.webdriver.common.keys import Keys
for value in all_codes:
code = driver.find_element_xpath('//*[#id="__layout"]//section[1]/div[1]//form/div/input')
code.send_key(value)
code.send_key(Keys.ENTER)
activation = driver.find_element_xpath('//*[#id="__layout"]//section[1]//form/div[2]/div/span')
if activation.text == '... some text ...':
break # exit loop before end of codes
You may need to use again find_element in every loop because find_element gives reference to object in memory and when you put code then it may change HTML and element can be moved in different place in memory.
You could also try to find shorter xpath with // or with classes or ids

Using .find(" ") method without cutting last character if the substring is at the very end

I am trying to find a substring which is a basically a link to any website. The idea is that if a user posts something, the link will be extracted and assigned to a variable called web_link. My current code is following:
post = ("You should watch this video https://www.example.com if you have free time!")
web_link = post[post.find("http" or "www"):post.find(" ", post.find("http" or "www"))]
The code works perfectly if there is a spacebar after the link, however, if the link inside the post is at the very end. For example:
post = ("You should definitely watch this video https://www.example.com")
Then the post.find(" ") can not find a spacebar/whitespace and returns -1 which results in web_link "https://www.example.co"
I am trying to find a solution that does not involve an if statement if possible.
Use regex. I've made a little change the solution here.
import re
def func(post):
return re.search("[(http|ftp|https)://]*([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?", post).group(0)
print(func("You should watch this video www.example.com if you have free time!"))
print(func("You should watch this video https://www.example.com"))
Output:
www.example.com
https://www.example.com
But I should say, using "if" is simpler and obvious:
def func(post):
start = post.find("http" or "www")
finish = post.find(" ", start)
return post[start:] if finish == -1 else post[start:finish]
The reason this doesn't work is because if the string isn't found and -1 is returned the slice commands interprets this as "the rest of the string -1 character from the end".
As ifma pointed out the best way to achieve this would be with a regular expression. Something like:
re.search("(https?://|www[^\s]+)", post).group(0)

How can I re-start code from the point that CSV write is completed?

I made a web crawler for this page (http://www.bobaedream.co.kr/cyber/CyberCar.php?gubun=I) to collect the stock list of each page and write information(e.g. photo url, title, description, date, price, etc.) in CSV.
Sometimes "exceptions" are randomly popped up while collecting the lists. When I re-start the entire code, sometimes the exception does not appear. I used "try and except" function inside of while loop to avoid the exception like below, but when the exception appears, the run continues in the while loop and can't get out of it.
while True:
try:
self.driver.execute_script(option2[1])
except (StaleElementReferenceException, NoSuchElementException):
sleep(1)
print("Exception Found")
continue
break
What I would like to do is to re-start the entire code from the last list written in CSV when the exception begins. My code is pretty long, so it is hard to describe exactly which part to be started. But, what I am wondering is if there is any specific command or logic to get the information of that last list in CSV and re-start the code from that point when the exception appears.I know my description is poor but can you guys give me any advice or something?
Well your question is not clear to me yet.
import csv
with open(filename) as f:
last_record = list(csv.reader(f))[-1]
You can use the above code to get the last record written in the csv file and use it accordingly. Please inform if its not the answer you wanted.

Checking if A follows B on twitter using Tweepy/Python

I have a list of a few thousand twitter ids and I would like to check who follows who in this network.
I used Tweepy to get the accounts using something like:
ids = {}
for i in list_of_accounts:
for page in tweepy.Cursor(api.followers_ids, screen_name=i).pages():
ids[i]=page
time.sleep(60)
The values in the dictionary ids form the network I would like to analyze. If I try to get the complete list of followers for each id (to compare to the list of users in the network) I run into two problems.
The first is that I may not have permission to see the user's followers - that's okay and I can skip those - but they stop my program. This is the case with the following code:
connections = {}
for x in user_ids:
l=[]
for page in tweepy.Cursor(api.followers_ids, user_id=x).pages():
l.append(page)
connections[x]=l
The second is that I have no way of telling when my program will need to sleep to avoid the rate-limit. If I put a 60 second wait after every page in this query - my program would take too long to run.
I tried to find a simple 'exists_friendship' command that might get around these issues in a simpler way - but I only find things that became obsolete with the change to API 1.1. I am open to using other packages for Python. Thanks.
if api.exists_friendship(userid_a, userid_b):
print "a follows b"
else:
print "a doesn't follow b, check separately if b follows a"

Categories

Resources