简体   繁体   English

找不到正确的 XPATH

[英]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. 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我们从同一个 html 元件中获得。

The XPATH I get is我得到的 XPATH 是

//*[@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他们得到的正确XPATH//div[contains(@aria-label, 'Tweet text')]并且当我在检查中检查它的位置时,它似乎是同一个元素

other's XPATH其他的 XPATH

No, try to avoid very long CSS or very long XPath expressions.不,尽量避免很长的 CSS 或很长的 XPath 表达式。 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.使用 XPath 是一种不好的做法,因为如果将元素移动到另一个 div 或 span - 您的 XPath 将被破坏。 Always prefer working with:总是喜欢与:

  1. CSS and ID CSS 和 ID
  2. CSS and Class CSS 和 Class
  3. CSS and attibutes CSS 和属性
  4. XPATH with text contains XPATH 含文字
  5. XPATH with match text (full match) XPATH 带匹配文本(完全匹配)
  6. If no other way possible - use only XPath如果没有其他可能 - 仅使用 XPath

Using the XPath, you can find an element in different ways.使用 XPath,您可以通过不同的方式找到元素。 It looks like you have copied the XPath generated by your browser.您似乎复制了浏览器生成的 XPath。 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. HTML元素通常具有唯一的参数,例如class,id,name等。所以你需要找到一个写一个简短的相对XPath。

For example, this element is the only one on the page that has a class "notranslate public-DraftEditor-content."例如,此元素是页面上唯一具有 class“notranslate public-DraftEditor-content”的元素。 So, the XPath could be:因此,XPath 可以是:

Xpath=//div[@class="notranslate public-DraftEditor-content"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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