Selenium 在 div 之后的段落中获取文本
Selenium get text in paragraph after div
我的页面如下所示:
当我们查看 HTML 代码时:
所以它首先在 div
中给出段落的标题,然后在它下面会有段落。所以理想情况下,我想做类似 driver.find_element_by_link_text('Objectives of the Course')
的事情,然后说 "get next element" (即它下面的段落)。
如何使用 selenium 或任何其他库完成此操作?
要提取标题 课程目标 下方 <p>
标签内的文本,您必须引入 WebDriverWait 对于 visibility_of_element_located()
并且您可以使用以下任一项 Locator Strategies:
使用 xpath 和 get_attribute()
:
print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='FieldsetBaslik' and contains(., 'Objectives of the Course')]//following::p[1]"))).get_attribute("innerHTML"))
使用 xpath 和 text
:
print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='FieldsetBaslik' and contains(., 'Objectives of the Course')]//following::p[1]"))).text)
结尾
根据文档:
get_attribute()
方法Gets the given attribute or property of the element.
text
属性returnsThe text of the element.
- Difference between text and innerHTML using Selenium
您可以使用 XPATH 或 CSS 选择器与 find_element_by_css_selector
方法
在此HTML:
<div class="title"> title </div>
<p> content </p>
你可以 select 下一个兄弟姐妹:
div.title + p {
color: red;
}
所以在你的情况下,driver.find_element_by_css_selector('div.FieldsetBaslik+p')
会起作用
检查此 link:https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator
我的页面如下所示:
当我们查看 HTML 代码时:
所以它首先在 div
中给出段落的标题,然后在它下面会有段落。所以理想情况下,我想做类似 driver.find_element_by_link_text('Objectives of the Course')
的事情,然后说 "get next element" (即它下面的段落)。
如何使用 selenium 或任何其他库完成此操作?
要提取标题 课程目标 下方 <p>
标签内的文本,您必须引入 WebDriverWait 对于 visibility_of_element_located()
并且您可以使用以下任一项 Locator Strategies:
使用 xpath 和
get_attribute()
:print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='FieldsetBaslik' and contains(., 'Objectives of the Course')]//following::p[1]"))).get_attribute("innerHTML"))
使用 xpath 和
text
:print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='FieldsetBaslik' and contains(., 'Objectives of the Course')]//following::p[1]"))).text)
结尾
根据文档:
get_attribute()
方法Gets the given attribute or property of the element.
text
属性returnsThe text of the element.
- Difference between text and innerHTML using Selenium
您可以使用 XPATH 或 CSS 选择器与 find_element_by_css_selector
方法
在此HTML:
<div class="title"> title </div>
<p> content </p>
你可以 select 下一个兄弟姐妹:
div.title + p {
color: red;
}
所以在你的情况下,driver.find_element_by_css_selector('div.FieldsetBaslik+p')
会起作用
检查此 link:https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator