python element finding method:
css를 이용하면 쉽게 찾을 수 있다. text 일부면, *=를 사용하고, full text의 경우, =만 사용하면 된다.
driver.find_element(By.XPATH, f'//td[contains(text(), "인증번호")]/following-sibling::td').text
driver.find_element(By.XPATH, f'//태그명[contains(text(), "포함텍스트")]/following-sibling::타겟태그명').text
파이썬 Selenium을 이용해서 특정 요소의 부모 요소 선택하기
파이썬 셀레니움을 이용해서 웹사이트를 제어하는 일을 생각해보면, 바로바로 내가 원하는 요소를 동작시켜서 일을 끝마치면 될 것 같습니다. 대개의 경우에는 이렇게 특정 요소를 바로 직접적
hogni.tistory.com
xpath에서 상위(부모) 노드를 접근하는 경로
UI 테스트 자동화를 짜던 중, 필요한 항목들에 각각 id 값이 존재하는 element를 발견했다. 다만, 라디오 버튼에 포함된 input 태그였기에 click 값을 주거나 send_keys로 enter를 넣어줘도 선택되지 않았다
velog.io
print(driver.find_element_by_xpath('//*[@id="container"]/main/div/div[2]/div[2]/div/table/tbody/tr[2]/td[2]').text) print(driver.find_element_by_xpath('//*[@id="container"]/main/div/div[2]/div[2]/div/table/tbody/tr[2]/td[2]').get_attribute('innerText'))
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
Text with leading/trailing spaces
In case the relevant text containing whitespaces either in the beginning:
<div> My Button</div>
or at the end:
<div>My Button </div>
or at both the ends:
<div> My Button </div>
In these cases you have two options:
- You can use contains() function which determines whether the first argument string contains the second argument string and returns boolean true or false as follows:
- my_element = driver.find_element_by_xpath("//div[contains(., 'My Button')]")
- You can use normalize-space() function which strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string as follows:
- driver.find_element_by_xpath("//div[normalize-space()='My Button']]")
XPath expression for variable text
In case the text is a variable, you can use:
foo= "foo_bar"
my_element = driver.find_element_by_xpath("//div[.='" + foo + "']")
You could try an XPath expression like:
'//div[contains(text(), "{0}") and @class="inner"]'.format(text)
((JavaScriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);
<속성 안의 단어를 검색하는 방법>
As per the HTML of the <iframe> element, it has the name attribute set as Dialogue Window. So to switch within the <iframe> you need to use the switch_to() method and you can use either of the following approaches:
- Using the name attribute of the <iframe> node as follows:
- # driver.switch_to.frame(‘frame_name’) driver.switch_to.frame("Dialogue Window")
- Using the <iframe> WebElement identified through name attribute as follows:
- driver.switch_to.frame(driver.find_element_by_name('Dialogue Window'))
- Using the <iframe> WebElement identified through css-selectors as follows:
- driver.switch_to.frame(driver.find_element_by_css_selector("iframe[name='Dialogue Window']"))
- Using the <iframe> WebElement identified through xpath as follows:
- driver.switch_to.frame(driver.find_element_by_xpath("//iframe[@name='Dialogue Window']"))
Ideally, you should induce WebDriverWait inconjunction with expected_conditions as frame_to_be_available_and_switch_to_it() for the desired frame as follows:
- Using NAME:
- WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"Dialogue Window")))
- Using CSS_SELECTOR:
- WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name='Dialogue Window']")))
- Using XPATH:
- WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@name='Dialogue Window']")))
Switching back from frame
- To switch back to the Parent Frame you can use the following line of code:
- driver.switch_to.parent_frame()
- To switch back to the Top Level Browsing Context / Top Window you can use the following line of code:
- driver.switch_to.default_content()
python 예제 코드
https://pcwpower.tistory.com/48
selenium chromedriver xpath 특정 속성을 가진 노드 찾기
selenium chromedriver xpath 특정 속성을 가진 노드 출처 : selenium-python.readthedocs.io/ 셀레니움을 통해 특정 HTML을 찾는 방법을 사용할때 가장 유용한 방법중 하나는 xpath를 사용하는 것입니다. 이걸 사용
pcwpower.tistory.com
driver.find_elements_by_xpath("//div[@*]")
셀레니움
- 특정 노드 내부
- / path to / element [@attribute_name]
- 문서의 어느 곳에서나
- // * [@ attribute_name]
- 특정 값을 가진 특정 노드 내부
- / path to / element [@ attribute_name = '검색 값']
- / path to / element [@ attribute_name = "검색 값"]
- 어떤 값을 가진 문서의 어느 곳에서나
- // * [@ attribute_name = '검색 문자열']
- // * [@ attribute_name = "검색 문자열"]
특정 Node 선택
표현 | 설명 |
* | 매칭 되는 모든 ElementNode |
@* | 매칭 되는 모든 속성Node |
Node() | 현재 Node로부터 문서상의 모든 Node를 조회 |
현재 Node와 관련되어 찾는 방법
축명 | 결과 |
ancestor | 현재 Node의 모든 ancestor( parent, grandparent,..etc)Node들을 선택 |
ancestor-or-self | ancestor + 현재Node |
Node() | 현재 Node로부터 문서상의 모든 Node를 조회 |
attribute | 현재 Node의 모든 속성Node |
child | 현재 Node의 모든 자식Node |
descendant | 현재 Node의 모든 자손Node(child, grandchild..etc) |
descendant-or-self | descendant + 현재Node |
following | 현재 Node의 닫기 태그 이후의 문서상 모든 Node |
following-sibling | 현재 Node 이후의 모든 siblingNode |
namespace | 현재 Node의 모든 namespaceNode |
parent | 현재 Node의 부모Node |
preceding | 현재 Node가 나타나기 이전의 모든 Node (ancestor, namespace, 속성Node 제외) |
preceding-sibling | 현재 Node 이전의 모든 siblingNode |
following-sibling | 현재 Node 이후의 모든 siblingNode |
self | 현재 Node 자기자신 |
iframe / 찾기 @@
ordernumberframe = driver.find_element_by_xpath("/html/body/div[3]/form[3]/div/table/tbody/tr[4]/td/iframe")
driver.switch_to.frame(ordernumberframe)
ordernumberframe1 = driver.find_element_by_id("se2_iframe")
driver.switch_to.frame(ordernumberframe1)
driver.find_element_by_xpath("/html/body/p").click()
driver.find_element_by_xpath("/html/body/p").send_keys(ordernumber)
time.sleep(1)
driver.switch_to.default_content()
driver.find_element_by_xpath("//input[@type='button' and @value='C/S 저장']").click()
셀레니움, XPath로 요소 찾기 표현식
[표현 기호]
nodename | nodename을 name으로 갖는 모든 요소 선택 |
/ | root 요소에서 선택 |
// | 현재 요소의 자손 요소를 선택. 현재 요소를 선택 |
.. | 현재 요소의 부모 요소를 선택 |
@ | 속성(attibutes) 선택 |
* | 모든 요소에 매치됨 |
@* | 모든 속성 요소에 매치됨 |
node() | 모든 종류 모든 요소에 매치됨 |
| | OR 조건 |
[예시]
---------------------------------------------------------------------------------------------------------
/div root 요소의 div 요소
./div 현재 요소의 자식 요소 중 div 요소
/* name에 상관없이 root 요소를 선택
./* 또는 * context 요소의 모든 자식 요소를 선택
//div 현재 웹페이지에서 모든 div 요소를 선택
.//div 현재 요소의 모든 자손 div 요소를 선택
//* 현재 웹페이지의 모든 요소를 선택
.//* 현재 요소의 모든 자손 요소를 선택
/div/p[0] root > div > p 요소 중 첫 번째 p 요소를 선택
/div/p[position()<3] root > div > p 요소 중 첫째, 둘째 p 요소 선택
/div/p[last()] root > div > p 요소 중 마지막 p 요소 선택
/bookstore/book[price>35.00]
root > bookstore > book 요소 중 price 속성이 35.00 초과 요소들 선택
//*[@id="tsf"]/div[2]/ id가 tsf인 모든 요소의 자식 div 요소 중 3번째 요소를 선택
//title | //price title 또는 price 요소를 선택
'Python' 카테고리의 다른 글
python winsound beep 소리 내기 (0) | 2023.02.04 |
---|---|
크롤링 checkbox 선택 및 해제 확인 하기 (1) | 2023.02.02 |
정규식 연습하기 좋은 사이트 (1) | 2022.12.12 |
pandas index 반환 (1) | 2022.07.30 |
Python .exe 실행 파일 만들기 (2) | 2022.07.03 |
댓글