Can not get file path from resource folder - Java
I try to automate a page that I have. In the page I need to upload a PDF file. The problem is that I want selenium via java will get the file from the resource of the project and not hard coded. (since some have windows and some mac and some ubonto so the solution is to get the path dynamically).
I manually hard coded I enter the path it worked and return the path, however to let java return the path it crash. this is my code:
/******* test *******/
public void testFileUpload() throws Exception {
WebDriver deiver2 = getWebDriver();
Thread.sleep(3000);
deiver2.switchTo()
.activeElement();
deiver2.findElement(By.xpath("//input[@type='file']"))
.sendKeys(
"X:\\project\\src\\test\\resources\\TAX12.pdf");
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("TAX12.pdf").getPath();
System.out.println("\n\n path is " + path);
System.out.println("END");
}
I want in the send keys to send the file, the exists however it is not worked. get null exception
the file exists in the folder and worked if manually set the path, but not locate the file if I want it to do it by himself (for win / mac / linux etc)
See also questions close to this topic
-
Leetcode, getting TLE after memoization, Palindrome Partitioning -2
Question -> https://leetcode.com/problems/palindrome-partitioning-ii/
Leetcode palindrome partitioning problem, getting TLE after memoization, provided my recursive approach as well in my question. Please correct me in this approach only.
The recursive approach will obviously give TLE, then I tried memoization approach, still getting tle even after memoizing . what else can I do to improve its complexity.
public int minCut(String s) { int[][] t = new int[s.length()+1][s.length()+1]; for(int i=0;i<=s.length();i++){ for(int j=0;j<=s.length();j++){ t[i][j] = -1; } } int ans = solve(s,0,s.length()-1,t); return ans; } public boolean isPalindrome(String s,int i,int j){ String str = s.substring(i,j+1); StringBuilder sb = new StringBuilder(str).reverse(); String sReverse = sb.toString(); if(sReverse.equals(str)){ return true; } return false; } public int solve(String s,int i,int j,int[][]t){ if(i>=j){ return 0; } if(isPalindrome(s,i,j)==true){ return t[i][j] = 0; } if(t[i][j]!=-1){ return t[i][j]; } int min = 2000; for(int k=i;k<=j-1;k++){ int temp = 1 + solve(s,i,k,t) + solve(s,k+1,j,t); if(temp<min){ min = temp; } } return t[i][j]= min; } } /* RECURSIVE APPROACH public int solve(String s,int i,int j){ if(i>=j){ return 0; } if(isPalindrome(s,i,j)==true){ return 0; } int min = 2000; for(int k=i;k<=j-1;k++){ int temp = 1 + solve(s,i,k) + solve(s,k+1,j); if(temp<min){ min = temp; } } return min; } */
-
Getters and Setters Java
Error 1.Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method setPerson is correct.
2.Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method getPerson is correct.How do I resolve these errors?
Here's my codeTestMain.java
1 import java.util.Scanner; 2 3 public class TestMain 4 { 5 public static void main(String args[]) 6 { 7 BusTicket ob = getTicketDetails(); 8 ob.calculateTotal(); 9 System.out.println("Ticket no:"+ob.getTicketNo()); 10 System.out.println("Passenger Name:"+ob.getName()); 11 System.out.println("Price of a ticket : "+ob.getTicketPrice()); 12 System.out.println("Total Amount : "+ob.getTotalAmount()); 13 } 14 public static BusTicket getTicketDetails() 15 { 16 Scanner sc = new Scanner(System.in); 17 BusTicket b = new BusTicket(); 18 19 System.out.println("Enter the passenger name:"); 20 String name = sc.nextLine(); 21 System.out.println("Enter the gender(M or F / m or f):"); 22 char gender = sc.next().charAt(0); 23 System.out.println("Enter the age:"); 24 int age = sc.nextInt(); 25 b.setPerson(name,gender,age); 26 System.out.println("Enter the ticket no:"); 27 b.setTicketNo(sc.nextInt()); 28 System.out.println("Enter the ticket price:"); 29 b.setTicketPrice(sc.nextFloat()); 30 return b; 31 } 32 }
BusTicket.java
1 public class BusTicket 2 { 3 private int ticketNo; 4 private float ticketPrice; 5 private float totalAmount; 6 private Person person = new Person(); 7 8 public void setTicketNo(int ticketNo) 9 { 10 this.ticketNo=ticketNo; 11 } 12 public int getTicketNo() 13 { 14 return this.ticketNo; 15 } 16 17 public void setTicketPrice(float ticketPrice) 18 { 19 this.ticketPrice=ticketPrice; 20 } 21 public float getTicketPrice() 22 { 23 return this.ticketPrice; 24 } 25 26 public void setPerson(String name,char gender,int age) 27 { 28 person.setName(name); 29 person.setGender(gender); 30 person.setAge(age); 31 } 32 public String getName() 33 { 34 return person.getName(); 35 } 36 37 38 public char getGender() 39 { 40 return person.getGender(); 41 } 42 43 44 public int getAge() 45 { 46 return person.getAge(); 47 } 48 49 public void setTotalAmount(float totalAmount) 50 { 51 this.totalAmount=totalAmount; 52 } 53 public void calculateTotal() 54 { 55 if(getAge()<16) 56 setTotalAmount(ticketPrice*(0.50f)); 57 else if(getAge()>=60) 58 setTotalAmount(ticketPrice*(0.75f)); 59 else if(getGender()=='F' || getGender()=='f') 60 setTotalAmount(ticketPrice*(0.90f)); 61 else 62 setTotalAmount(ticketPrice); 63 } 64 public float getTotalAmount() 65 { 66 return this.totalAmount; 67 } 68 }
Person.java
1 public class Person 2 { 3 private String name; 4 private char gender; 5 private int age; 6 7 public void setName(String name) 8 { 9 this.name=name; 10 } 11 public String getName() 12 { 13 return this.name; 14 } 15 16 public void setGender(char gender) 17 { 18 this.gender=gender; 19 } 20 public char getGender() 21 { 22 return this.gender; 23 } 24 25 public void setAge(int age) 26 { 27 this.age=age; 28 } 29 public int getAge() 30 { 31 return this.age; 32 } 33 }
-
Is there a way to convert data collected from Opencv's facial landmarks and translate the points to a 3d model
I have successfully started my journey in Opencv as part of my machine learning adventure, one topic I find interesting is facial landmarks which are able to trace out 64 or more points on a humans face, I would like to know if I can transfer the data that Opencv is collecting from those landmarks on to a 3d human face model to mimic whatever the individual is doing, similar to Apple's Animoji, any library or API in Java or C++ that could perform this action would be greatly appreciated.
-
Adopting code from Oddsportal URL to current & Next Page
I have a code that scrapes
https://www.oddsportal.com/soccer/england/premier-league/
odds and event data.
I want to adopt the same to get all data for "today" which is reflected at
https://www.oddsportal.com/matches/soccer/
and 'tomorrow' is
https://www.oddsportal.com/matches/soccer/20210309/
which is essentially
url/today+1
My current code that works is:
browser = webdriver.Chrome() browser.get("https://www.oddsportal.com/soccer/england/premier-league/") df = pd.read_html(browser.page_source, header=0)[0] dateList = [] gameList = [] home_odds = [] draw_odds = [] away_odds = [] for row in df.itertuples(): if not isinstance(row[1], str): continue elif ':' not in row[1]: date = row[1].split('-')[0] continue time = row[1] dateList.append(date) gameList.append(row[2]) home_odds.append(row[4]) draw_odds.append(row[5]) away_odds.append(row[6]) result = pd.DataFrame({'date': dateList, 'game': gameList, 'Home': home_odds, 'Draw': draw_odds, 'Away': away_odds})
Because the
datelist[]
is different to the links e.g.Algeria»Ligue 1
I am getting an errorNameError: name 'date' is not defined
How can I adopt the same to
https://www.oddsportal.com/matches/soccer/
and for
tomorrow
? -
How do I download an jsp file into a pdf with selenium?
I need to download the jsp inside of an iframe using selenium. It has to be in a pdf format.
How do I manage to do this?
<iframe id="miBody" name="miBody" src="/padron-puc-constancia-internet/jsp/Constancia.jsp" height="150%" width="100%" scrolling="auto" frameborder="0" marginwidth="0" marginheight="0" align="top" style="height: 629px;"></iframe>
-
Headless Chrome driver unable to fetch Instagram page in python Selenium driver
I tried to login and scrape a few details from my Instagram page in Python. I wanna do it in the headless mode because I'm going to deploy it in Heroku. So when I try to login using this code in the headless Chrome driver, the Instagram login page is not fetched. I have provided the screenshot also.
def login_insta(driver,username,password): driver.get("https://www.instagram.com/accounts/login") time.sleep(5) driver.save_screenshot('scrnsh.png') driver.find_element_by_xpath( "//input[@name='username']").send_keys(username) driver.find_element_by_xpath( "//input[@name='password']").send_keys(password) driver.find_element_by_xpath("//button/div[text()='Log In']").click() print("Logged in") options = Options() PATH = r"C:\Users\pcname\Downloads\chromedriver" options.add_argument("--headless") options.add_argument("--disable-dev-shm-usage") options.add_argument("--no-sandbox") options.add_argument('--disable-gpu') driver = webdriver.Chrome(executable_path=PATH, chrome_options=options) login_insta(driver,"name","pass")
The screenshot said "Error Please wait a few minutes before you try again" This error doesn't occur with the headlesss Firefox driver, I don't how to add Firefox buildpacks in Heroku. I have recent Chrome driver version. Please help me solve this issue.
Or if you can suggest buildpacks for Firefox for Heroku, and the steps to add them, it would be very helpful. Thank you!
-
Gather usernames in instagram
the main problem is i want to gather and get usernames of who liked my posts, who saw my story and ...
when i have list of these usernames, i can understand who is ghost in my followers and who is loyal to me and ....
i wrote something with
selenium
, it would login to Instagram. but i can't and i don't know how to save any username in it. any idea?from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--user-data-dir=chrome-data") browser = webdriver.Chrome(options=chrome_options) browser.get('https://www.instagram.com/p/CMAVjR5CmOx/') c2 = browser.find_element_by_xpath("/html/body/div[1]/section/main/div/div[1]/article/div[3]/section[2]/div/div[2]/a") c2.click() c3 = browser.find_element_by_xpath("/html/body/div[5]/div/div/div[2]/div/div/div[1]/div[2]/div[2]/div").text print(c3)
-
Unable to open Edge (Chromium) with Selenium 4 beta1: Failed to open file to mark as storage reserve
The error I get is:
[23000:16844:0307/110159.932:ERROR:storage_reserve.cc(164)] Failed to open file to mark as storage reserve: C:\Users***\AppData\Local\Temp\scoped_dir6336_66835013\Default\Code Cache\js
My code is:
using (var service = EdgeDriverService.CreateChromiumService("path-to-msedgedriver", "msedgedriver.exe")) { service.UseVerboseLogging = true; var driver = new EdgeDriver(service); driver.Navigate().GoToUrl("https://google.com"); }
Below is the verbose log:
Starting MSEdgeDriver 89.0.774.45 (bb55f48a0d369c43828d1b214a80c5166f640ee2) on port 60879 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping MSEdgeDriver safe. MSEdgeDriver was started successfully. [1615143719.657][INFO]: [21575b2e1a8cef14f7f2720d64a564ea] COMMAND InitSession { "capabilities": { "firstMatch": [ { "browserName": "MicrosoftEdge", "ms:edgeChromium": true, "ms:edgeOptions": { } } ] } } [1615143719.662][INFO]: Populating Preferences file: { "alternate_error_pages": { "enabled": false }, "autofill": { "enabled": false }, "browser": { "check_default_browser": false }, "distribution": { "import_bookmarks": false, "import_history": false, "import_search_engine": false, "make_chrome_default_for_user": false, "skip_first_run_ui": true }, "dns_prefetching": { "enabled": false }, "profile": { "content_settings": { "pattern_pairs": { "https://*,*": { "media-stream": { "audio": "Default", "video": "Default" } } } }, "default_content_setting_values": { "geolocation": 1 }, "default_content_settings": { "geolocation": 1, "mouselock": 1, "notifications": 1, "popups": 1, "ppapi-broker": 1 }, "password_manager_enabled": false }, "safebrowsing": { "enabled": false }, "search": { "suggest_enabled": false }, "translate": { "enabled": false } } [1615143719.667][INFO]: Populating Local State file: { "background_mode": { "enabled": false }, "ssl": { "rev_checking": { "enabled": false } } } [1615143719.673][INFO]: Launching msedge: "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --disable-background-networking --disable-backgrounding-occluded-windows --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --enable-automation --enable-blink-features=ShadowDOMV0 --enable-logging --log-level=0 --no-first-run --no-service-autorun --password-store=basic --remote-debugging-port=0 --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\***\AppData\Local\Temp\scoped_dir6336_66835013" data:, [23000:16844:0307/110159.932:ERROR:storage_reserve.cc(164)] Failed to open file to mark as storage reserve: C:\Users\***\AppData\Local\Temp\scoped_dir6336_66835013\Default\Code Cache\js DevTools listening on ws://127.0.0.1:60883/devtools/browser/07a9534e-f965-4cbf-83c5-c13beee5ca35 [1615143720.557][DEBUG]: DevTools HTTP Request: http://localhost:60883/json/version [1615143720.862][DEBUG]: DevTools HTTP Response: { "Browser": "Edg/89.0.774.45", "Protocol-Version": "1.3", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36 Edg/89.0.774.45", "V8-Version": "8.9.255.20", "WebKit-Version": "537.36 (@bb55f48a0d369c43828d1b214a80c5166f640ee2)", "webSocketDebuggerUrl": "ws://localhost:60883/devtools/browser/07a9534e-f965-4cbf-83c5-c13beee5ca35" } [1615143720.863][DEBUG]: DevTools HTTP Request: http://localhost:60883/json/list [1615143720.871][DEBUG]: DevTools HTTP Response: [ ]
-
How to set browser width and height in Selenium WebDriver?
I try to set bowser size to a certain dimensions using:
browser = webdriver.Chrome() browser.set_window_position(100, 100) browser.set_window_size(1024, 768)
but it seems webdriver ignores Y parameter - window is correctly shifted 100 points from the left, but the 100 points from the top are ignored. The most annoying is that Y dimension is ignored too - window height is set to 2035 points (4K monitor height minus taskbar) (Linux x86_64, KF5, Python 3.9.1, Selenium 3.141.0). I've seen solution with just maximizing the window, but having window 6 time larger than necessary seems no OK. Currently I create virtual desktop of appropriate size and then maximise window on it, but I don't think its sustainable solution.
-
Getting "Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR" while running Python Selenium test scripts
I am running the test scripts with chrome browser using python selenium test scripts.
chromedriver = '.\\chromedriver.exe' options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--incognito') options.add_argument('--disable-gpu') options.add_argument("--no-sandbox") options.add_argument('--ignore-certificate-errors') options.add_argument('window-size=1920x1080')
Cannot share the whole code but I have used sleep, implicit and explicit waits to slow down the webpage loads but still I am getting different failures in each time. The least errors I have seen is 6 out of 120 test cases and there is only 1 of them is a real failure. I thought about AJAX failure so I have added the waits mentioned above but still cannot trust the test scripts.
I am taking the screenshots of the failures and my only option would be to run the failed test cases one more time to see if they would pass.
Any suggestions are welcomed. Thank you for your time.
-
Selenium ChromeDriver Action and SendKeys don´t press the button
I have a problem with my SeleniumDriver and it drives me crazy. I almost tried every solution on stackoverflow..
My simple goal is to send a key to the browser, but not to an element. My key is "mediaTrackNext" and can be found at
Windows.Forms.Keys.MediaNextTrack
I tried almost any solution:
Dim actions As Actions = New Actions(TestBot) actions.SendKeys(Windows.Forms.Keys.MediaNextTrack).Perform()
or
TestBot.FindElement(By.XPath("/html/body")).SendKeys(Windows.Forms.Keys.MediaNextTrack)
or
Dim actions As Actions = New Actions(TestBot) actions.SendKeys(TestBot.FindElement(By.XPath("//body")), Keys.F12).Perform()
I can´t even send keys like F12 to open the developers console, nothing happens.. F5 doesn´t work as well. And yes, I tried a few Tags and xpaths, but no tag seem to work.
Is there another way? I am so stuck right now..
Thank you. Best regards, xored