I am currently finding the XPATH for the input area on twitter so that i could write smth on it using bot but i keep getting the wrong XPATH.However,i've seen the code from other ppl and they manage to get the correct XPATH eventhough we are getting from the same html element.
The XPATH I get is //*[@id="reactroot"]/div/div/div2/main/div/div/div/div1/div/div2/div/div2/div1/div/div/div/div2/div1/div/div/div/div/div/div2/div/div/div/div/label/div1/div/div/div/div/div/div2/div
The correct XPATH they get is //div[contains(@aria-label, 'Tweet text')] and when i check the location of it in inspect , it appears to be the same element
CodePudding user response:
No, try to avoid very long CSS or very long XPath expressions. They are hard to read, not reliable and also makes your code ugly.
Try this:
my_element = driver.find_element(By.XPATH, '//div[contains(text(),"What\'s happening")]')
or:
my_element = driver.find_element(By.CSS, '//div[data-testid="tweetTextarea_0"]')
Using XPath is a bad practice because if the element will be moved to another div or span - your XPath will be broken. Always prefer working with:
- CSS and ID
- CSS and Class
- CSS and attibutes
- XPATH with text contains
- XPATH with match text (full match)
- If no other way possible - use only XPath
CodePudding user response:
Using the XPath, you can find an element in different ways. It looks like you have copied the XPath generated by your browser. But it's a bit massive. HTML elements usually have unique parameters such as class, id, name, etc. So you need to find one to write a short relative XPath.
For example, this element is the only one on the page that has a class "notranslate public-DraftEditor-content." So, the XPath could be:
Xpath=//div[@]