Selenium - unable to submit comment - python

I am trying to write a script that would allow me to submit comments to a news website programmatically.
I am using Selenium and here is my scrip (with the exact link I am trying to work with):
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
url = "https://www.delfi.lt/en/lifestyle/earth-day-events-for-the-spring-equinox.d?id=87005127"
driver.get(url)
# Clicking 'I agree' on a cookies banner:
cookies_ok = '//*[#id="c-right"]/a'
driver.find_element_by_xpath(cookies_ok).click()
# XPath list
anon = '//*[#id="comments-listing"]/div[2]/div/div[2]/div/ul/li[1]/span'
name = '//*[#id="inputDiv"]/div/form/input'
comment = '//*[#id="inputDiv"]/div/form/div[3]/div/textarea'
button = '//*[#id="inputDiv"]/div/form/div[4]/div[2]/button[1]'
# Click 'Anonymous' -> fill name and comment fields -> press PUBLISH
driver.find_element_by_xpath(anon).click()
driver.find_element_by_xpath(name).send_keys('name')
driver.find_element_by_xpath(comment).send_keys('comment')
driver.find_element_by_xpath(button).click()
Everything works, but when I the last command is executed, I am getting this message on the website:
"Cookies are blocked or not supported by your browser". However, when I follow the same steps myself in browser, there are no issues with cookies.
Any ideas on how to prevent this error?
Thanks

try using this
driver = webdriver.Chrome(executable_path=webdriver_manager.chrome.ChromeDriverManager().install())
This will install the latest chrome browser and your test will run.
You may need to install webdriver-manager by using pip install webdriver-manager

You may optimize the code and I assume you have to latest binaries :
driver = webdriver.Chrome("C:\\Users\\***\\Desktop\\Selenium+Python\\chromedriver.exe")
driver.maximize_window()
wait = WebDriverWait(driver, 30)
driver.get("https://www.delfi.lt/en/lifestyle/earth-day-events-for-the-spring-equinox.d?id=87005127")
wait.until(EC.element_to_be_clickable((By.XPATH, "//*[#id='c-right']/a"))).click()
ActionChains(driver).move_to_element(wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "li.as-link:first-child")))).click().perform()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.input-name"))).send_keys("denisafonin")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "textarea.input-message"))).send_keys("Your comment")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.input-login"))).click()

Related

Python Selenium "Unable to locate element"

I am trying to use Selenium to sign up an email account automatically whenever I need to. It's just a fun learning project for me. For the life of me I don't understand why it can't find the element. This code works fine on the sign-in page but not the sign-up page. I have tried all different Selenium commands and even tried using the ID and class name. Either is says it can't locate the element or that it is not reachable by keyboard.
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import time
options = Options()
driver = webdriver.Firefox(options=options, executable_path=r'geckodriver.exe')
driver.get("https://mail.protonmail.com/create/new?language=en")
time.sleep(10)
username_input = driver.find_element_by_id("username").send_keys("testusername")
Also here is the HTML code: https://i.imgur.com/ZaBMTzG.png
The username field is in iframe, you need to switch to iframe to make this work.
Below is the code that works fine :
driver.get("https://mail.protonmail.com/create/new?language=en")
driver.switch_to.frame(driver.find_element_by_css_selector("iframe[title='Registration form'][class='top']"))
driver.find_element_by_id("username").send_keys("some string")
read more about iframe here
learn more about how to switch to iframe/frame/framset using Python
selenium Bindings here
Update :
wait = WebDriverWait(driver, 30)
driver.get("https://mail.protonmail.com/create/new?language=en")
driver.switch_to.frame(driver.find_element_by_css_selector("iframe[title='Registration form'][class='top']"))
driver.find_element_by_id("username").send_keys("some string")
driver.switch_to.default_content()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(5)
driver.switch_to.frame(driver.find_element_by_css_selector("iframe[title='Registration form'][class='bottom']"))
wait.until(EC.element_to_be_clickable((By.NAME, "submitBtn"))).click()
I'm not sure if I've seen enough code to diagnose, but I think the way you are defining username_input seems problematic. driver.find_element_by_id("username").send_keys("testusername") doesn't actually return anything so it seems like you are setting username_input = null.

python requests download trough download button on page

So I am creating an application were you can download files trough a link. This webpage contains a download button and that needs to be pressed in order to start the download. This is the link where you can reference to: link. My code:
link = input("enter link: ")
r = requests.get(link, allow_redirects=True)
how can I make requests or any other library click on the download button and save this file?
Using selenium:
INSTALLATION
Skip this if you already have selenium installed.
Install Selenium, type the following in your terminal: pip3 install selenium
Now you need a webdriver for Selenium. If you are wanting to use Chrome, firstly type "chrome://version/" in your browser and find the version you are using. Then go to this link and download the appropriate webdriver for your browser. If you are using a different browser, like Firefox for example, just type selenium [your browser] webdriver.
Installation docs
CODE
Now for the code (following code is for Chrome, you would only need to change driver = webdriver.Chrome() if you are using a different webdriver):
from selenium import webdriver #importing webdriver
PATH = "C:/path/to/chromedriver" #webdriver location
driver = webdriver.Chrome(PATH)
link = input("Enter link: ")
driver.get(link) #going to URL
driver.find_element_by_xpath("/html/body/div/main/div[3]/div/div/div/div/div[2]/div[2]/span/button")\
.click() #clicking on the button
I used full xpath to locate the button, but you can use multiple things as seen in the documentation.

How to assert/verify successful login using Python / Selenium Webdriver

I have done a little research and could not find any answer specific to Selenium WebDriver with Python.
I can successfully sign into the page but I cannot find way(s) to verify that the login was successful. Page title does not work for me since it does not change.
Python Selenium documentation does not have any good explanation or examples.
All I want to do after this code is to put a line and assert that the username "Tuto" is visible on the page
LoginButtonLocator = "//a[contains(text(), 'Login')]"
facebookConnectButtonLocator = "//a[contains(text(), 'Connect with Facebook')]"
facebookLoginLocatorID = "email"
facebookPasswordLocatorID = "pass"
facebookLoginButtonLocatorID = "loginbutton"
LoginButtonElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(LoginButtonLocator))
LoginButtonElement.click()
facebookConnectButtonElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(facebookConnectButtonLocator))
facebookConnectButtonElement.click()
facebookLoginElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_id(facebookLoginLocatorID))
facebookLoginElement.send_keys(facebookID)
facebookPasswordElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_id(facebookPasswordLocatorID))
facebookPasswordElement.send_keys(facebookPW)
facebookLoginButtonElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_id(facebookLoginButtonLocatorID))
facebookLoginButtonElement.click()
I am working with the Javascript API instead of the Python version, so the syntax is different, but here is how I would get about it (using mocha as a test framework):
facebookLoginButtonElement.click().then(function(_) {
driver.findElement(By.xpath('//a[text() = "Tuto"]')).then(function(userLink) {
assert.ok(userLink);
});
});
In the javascript version, if <a ...>Tuto</a> can't be found there would be an error before the callback is called, so the assertion would be redundant (would only get there if the link was found), but I find it as self-documenting so I add the assert.
Just try to find an element using xPath:
wait = WebDriverWait(browser, 10)
find_username = wait.until(EC.presence_of_element_located((By.XPATH,'//span[contains(text(), "Alex")]')))
assert find_username
Hope, it will help you.
I'm writing it considering that you are using webdriver_manager for Chrome, though it doesn't create many effects, You can use the code in both scenarios with webdriver_manager or without as well provided that you have made significant changes in adding executable path for webdriver if not using webdriver_manager. Here you go...
from selenium import webdriver
// this was for importing webdriver
from webdriver_manager.chrome import ChromeDrivermanager
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://somedummy.domain.com/login")
driver.find_element_by_name("username").send_keys("somedummyvalidated#email.com")
driver.find_element_by_name("password").send_keys("someDummyPass")
driver.find_element_by_id("btnLogin").click()
this block was about sending keys, now if you are logged in correctly then the page title must change. Just use the below code to fetch the title and use assert or match the titles before and after login.
driver.title

why blank page opens in firefox when run with selenium for the first time?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
#driver.set_preference("browser.startup.homepage_override.mstone", "ignore")
driver.get("https://url.aspx/")
username = driver.find_element_by_name("SchSel$txtUserName")
username.clear()
username.send_keys("username")
username.send_keys(Keys.RETURN)
password = driver.find_element_by_name("SchSel$txtPassword")
password.clear()
password.send_keys("pass")
password.send_keys(Keys.RETURN)
driver.get("https://.aspx")
assert "Welcome" in driver.page_source
driver.close()
I am running selenium for the first time .How many times I try blank page opens in fireFox
selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.
I think I had a similar problem and used the info at this link to help:
https://stackoverflow.com/a/30103931/6582364
Basically it suggests using xvfb and pyvirtualdisplay which wraps the firefox browser. Link also contains sample code. Doesn't take too long to install and get running but worked for me.
Hope this works for you too.

Facebook account download automation with python?

As a regular task within my job role i often have to download full Facebook accounts from within a users account. I am trying to improve my workflow and automate this if i can.
I have tried searching for this topic on the site and although many cover the login part i am yet to locate a question that deals with the popup windows of Facebook. If i am wrong i apologise and please amend the post accordingly.
As a starting point i have decided to start learning python and am using this to script the process with a little help from selenium and Chrome Driver. I have managed to write the code to login and navigate to the correct page and click the initial link 'download a copy'. I am struggling however to get the script to locate and click the 'Start My Archive' button within the popup window.
Here is the code that i have used so far including the several alternative code blocks that i have tried commented out at the bottom:
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#Global Variables
target = "john.doe.7"
username = "john#doe.com"
password = "Password"
sleep = 5
#Finds and locates the ChromeDriver
driver = webdriver.Chrome("C:\Python35-32\ChromeDriver\chromedriver.exe")
#Set Chrome Options
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
#Directs browser to webpage
driver.get('http://www.facebook.com');
#code block to log in user
def logmein():
search_box = driver.find_element_by_name('email')
search_box.send_keys(username)
search_box = driver.find_element_by_name('pass')
search_box.send_keys(password)
search_box.submit()
#code to go to specific URL
def GoToURL(URL):
time.sleep(sleep) # Let the user actually see something!
driver.get(URL);
logmein()
GoToURL('https://www.facebook.com/'+'settings')
link = driver.find_element_by_link_text('Download a copy')
link.click()
#driver.find_element_by.xpath("//button[contains(., 'Start My Archive')]").click()
#driver.find_element_by_css_selector('button._42ft._42fu.selected._42gz._42gy').click()
#driver.find_element_by_xpath("//*[contains(text(), 'Start My Archive')]").click()
#driver.find_element_by_css_selector('button._42ft._42fu.layerConfirm.uiOverlayButton.selected._42g-._42gy').click()
#from selenium.webdriver.common.action_chains.ActionChains import driver
#buttons = driver.find_elements_by_xpath("//title[contains(text(),'Start My Archive')]")
#actions = ActionChains(self.driver)
#time.sleep(2)
#actions.click(button)
#actions.perform()
Just add this to your code and run if it is working or not. Always use CssSelector.
Look i ran the below code in eclipse with java and I'm not aware of python so if something is wrong in syntax , i apologies. Just Try this and see.
driver.implicitly_wait(10)
Startmyarchive = driver.find_element_by_css_selector("._42ft._42fu.selected._42gz._42gy")
Startmyarchive.click()
driver.implicitly_wait(10)
Acknowledge = driver.find_element_by_css_selector("._42ft._42fu.layerConfirm.uiOverlayButton.selected._42g-._42gy")
Acknowledge.click()
driver.implicitly_wait(10)
ClickOkay = driver.find_element_by_css_selector("._42ft._42fu.layerCancel.uiOverlayButton.selected._42g-._42gy")
ClickOkay.click()
Happy Learning :-) Do reply back for any query.

Categories