TIL

[Eng/Kor] X path

0_hoonie 2022. 1. 4. 19:20

If you run your code successfuly, you have to use many kinds of elements. (e.g id, name, class and so on)

So you have to type your code case by case. However, X path makes you use one way.

 

driver.find_element_by_xpath("//*[@id='Top1_TABSearchLink']").click() 
# go to link thourgh Xpath
driver.find_element_by_id("Top1_TABSearchLink").click()
#go to link through ID Element

 For example above, whatever you use any element, you can replace to xpath. It works as the same.

 

*Caution

If you use xpath, you have to replace ""(quotation mark) to '' in xpath route. It makes error.

    driver.find_element_by_xpath("//*[@id="rso"]/div[1]/div/div/div/div/div/div/div[1]/a").click()
                                 ^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

 

 

 

 


Xpath는 생각보다 되게 유용한 것 같다. 매번 해당 링크의 id, name 등 element를 재설정 해줄 필요없이 다 일괄로 find_element_by_xpath로 대체 가능하다. 실제로 동작도 똑같이 된다. 그리고 xpath안에 element 가 명기되어있기 때문에 어느정도 식별하는데에도 크게 문제가 되지 않는다.

 

아래와 같이 HTML 소스가 있을때 해당 소스를 xpath로 붙여넣는거나, id element로 사용하는거나 똑같은 결과가 나온다.

driver.find_element_by_xpath("//*[@id='Top1_TABSearchLink']").click() 
#Xpath를 통해 해당 링크로 접속
driver.find_element_by_id("Top1_TABSearchLink").click()
#ID Element를 통해 해당 링크로 접속