简体   繁体   中英

Couldn't find the correct XPATH

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/div[2]/main/div/div/div/div[1]/div/div[2]/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

Element chosen

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

other's XPATH

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:

  1. CSS and ID
  2. CSS and Class
  3. CSS and attibutes
  4. XPATH with text contains
  5. XPATH with match text (full match)
  6. If no other way possible - use only XPath

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[@class="notranslate public-DraftEditor-content"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM