Hola lector de mi blog. Una amistad me ha pedido un bot que realice actividades automáticas en su cuenta de Facebook, dicha cuenta de Facebook se encargara de realizar promociones y publicaciones de contenido comercial.
Eso si, no puedo compartir todo el script con ustedes porque hay información de carácter comercial que fue denegado en compartir y eso podría generar una malinterpretación o problemas de ejecución en el momento de hacer funcionar las cosas en sus proyectos. Por esa razón tomé la decisión de compartir una pequeña parte. Que este pequeño proyecto es valioso para mí, por qué no soy de usar Selenium, realmente es la primera vez que lo uso y tengo varios días consultando documentación para comprender con lujos y detalles cada paso que avanzo en el desarrollo de este pequeño proyecto.
Quizás en otro momento pueda hacer un script más completo y de mejor elaboración para compartir con ustedes que puedan usarlo de referencia para sus elaboraciones.
Como muchos sabrán, Selenium es un framework de desarrollado orientado a crear pruebas de software automatizado en sitios web con el propósito de interactuar con elementos o contenido que presenta un sitio. Por ejemplo, puede usarse para hacer clics en imágenes, completar formularios, descargar archivos, etc. Todo esto es muy útil para cuando necesitamos realizar tareas repetitivas que nos puede resultar agotador o incluso producir daños en la salud. Bueno, al conocer sobre esto, contacte a un amigo para decirle que era capaz de hacer un programa para su trabajo, le pareció excelente la idea y cree todo el marco de desarrollo basado en Selenium.
El proyecto lo entregué ayer en la noche y los resultados han sido positivos, hasta ahora sin ninguna novedad. Mi amigo está muy contento porque ahora puede dedicar horas extras para dedicarse a otros asuntos personales y se siente agradecido lo que para mí me anima mucho, ahora quiero hacer más proyectos en Selenium y lo haré en cuanto atienda ocupaciones personales.
Volviendo al propósito principal. Cuando revisen el código notaran que existe dos nombres de variables; la primera es username y password. En la primera colocas tu nombre de usuario o dirección de correo electrónico y en la segunda, colocas tu contraseña de acceso. Es decir, debes de reemplazar **add your username y add your password por los datos de acceso a tu cuenta de Facebook. Solamente con reemplazarlos ya podrás iniciar sesión en tu cuenta de Facebook, ¡Así de simple!
Nota: el parámetro options.add_argument(r"--user-data-dir=C:\Users\owner\AppData\Local\Microsoft\Edge\User Data\Profile 1") debes eliminarlo si te causa problemas. Lo agregué porque hay un pequeño truco que descubrí; si exporto mis datos de la caché del navegador de un perfil(este caso use el Profile 1), note que la velocidad de carga es más rápida y además, evito la aburrida tarea de tener que agregar los datos de acceso una y otra vez, lo que implica ahorrarme un problema con los servicios de Facebook debido a los inicios de sesión recurrentes en el webdrive de Selenium.
Otra cosa, use la interfaz de Facebook Mobile porque tiene una carga más rápida(No olviden que mi conexión a internet es inestable y eso a veces me trae problemas).
Y bueno, querido lector de mi blog, doy por culminada esta pequeña entrega. De verdad quisiera compartirles este proyecto completo para ti, pero por ahora será una pequeña parte. Espero que pronto me vuelva a salir otro proyecto capaz de ejecutarlo en esta máquina obsoleta, así demuestro mi habilidad de desarrollo básico en Python, porque soy programador en formación.
Espero que esta entrega te haya gustado, puedes dejar comentarios y con gusto te responderé. Hasta la próxima entrega. Gracias por tu tiempo.
Este programa fue ejecutado con Python 3.9.13 en el sistema operativo Windows 10.
Hello reader of my blog. A friend has asked me for a bot to perform automatic activities in his Facebook account, this Facebook account will be responsible for promotions and publications of commercial content.
However, I can not share the whole script with you because there is commercial information that was denied to share and that could generate a misinterpretation or execution problems at the time of running things in their projects. For that reason I made the decision to share a small part of it. That this small project is valuable for me, because I am not a Selenium user, it is really the first time I use it and I have several days consulting documentation to understand in detail each step that I advance in the development of this small project.
Perhaps in another moment I can make a more complete and better elaborated script to share with you that you can use it as a reference for your elaborations.
As many will know, Selenium is a framework developed oriented to create automated software tests in web sites with the purpose of interacting with elements or content that presents a site. For example, it can be used for clicking on images, filling out forms, downloading files, etc. All of this is very useful for when we need to perform repetitive tasks that can be tiring or even harmful to our health. Well, knowing about this, I contacted a friend to tell him that I was able to make a program for his work, he thought it was an excellent idea and I created the whole development framework based on Selenium.
I delivered the project last night and the results have been positive, so far without any news. My friend is very happy because now he can dedicate extra hours to dedicate to other personal matters and he feels grateful which for me encourages me a lot, now I want to do more projects in Selenium and I will do it as soon as I attend to personal occupations.
Back to the main purpose. When you review the code you will notice that there are two variable names; the first one is username and password. In the first one you put your username or email address and in the second one, you put your access password. In other words, you must replace **add your username and add your password with the access data to your Facebook account. Just by replacing them you will be able to log in to your Facebook account, it's as simple as that!
Note: The options.add_argument(r"--user-data-dir=C:\Users\owner\AppData\Local\Microsoft\Edge\User Data\Profile 1") parameter should be removed if it causes problems. I added it because there is a little trick that I discovered; if I export my browser cache data from a profile (in this case use Profile 1), I notice that the loading speed is faster and also, I avoid the boring task of having to add the access data again and again, which means saving me a problem with facebook services due to recurring logins in selenium webdrive.
Another thing, use the Facebook Mobile interface because it has a faster loading (Don't forget that my internet connection is unstable and that sometimes brings me problems).
And well, dear reader of my blog, I conclude this little installment. I would really like to share this complete project with you, but for now it will be a small part. I hope that soon I will get another project capable of running it on this obsolete machine, thus showing my basic development skills in Python, because I am a programmer in training.
I hope you liked this delivery, you can leave comments and I will gladly answer you. Until the next installation. Thanks for your time.
This program was run with Python 3.9.13 on Windows 10 operating system.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from msedge.selenium_tools import Edge, EdgeOptionsusername = "add your username"
password = "add your password"options = EdgeOptions()
options.add_argument("start-maximized")
options.add_argument("--disable-notifications")
options.add_argument(r"--user-data-dir=C:\Users\owner\AppData\Local\Microsoft\Edge\User Data\Profile 1")
options.use_chromium = True
driver=Edge(executable_path=r'C:\edgedriver\msedgedriver.exe',options=options)
driver.get("https://m.facebook.com/login/")insert_username = driver.find_element(By.NAME, 'email')
insert_password = driver.find_element(By.NAME, 'pass')
insert_username.send_keys(username)
insert_password.send_keys(password)
insert_password.send_keys(Keys.ENTER)
wait_onetouch = WebDriverWait(driver, 60)fin_onetouch=wait_onetouch.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#root > div._7om2 > div > div > div._7om2._2pip > div:nth-child(1) > div > div > a')))
dont_save_one_touch = driver.find_element(By.CSS_SELECTOR,'#root > div._7om2 > div > div > div._7om2._2pip > div:nth-child(1) > div > div > a')
dont_save_one_touch.click()
driver.quit()