提问人:Jawad Ahmad Khan 提问时间:12/24/2019 更新时间:12/24/2019 访问量:45
如何使用带有 selenium 和 python 绑定的 xpath 仅提取不在任何标签内的文本
How to extract only the text which is not inside any tag using xpath with selenium and python binding
问:
这是我的目标html:
<p><strong>Contact:</strong>
Garmendia, Diane
<br>
<strong>Email:</strong> <a href="mailto:[email protected]">[email protected]</a><br>
<strong>P:</strong> 805-957-9100<br>
<strong>F:</strong> 805-957-4191<br>
<a href="http://www.33jewels.com">http://www.33jewels.com</a>
<!-- <b>Email Link:</b> $MC:EMAILLINKTOFORM$ -->
</p>
我需要使用 xpath 表达式提取“Garmendia, Diane”。
我试过使用:
cname=driver.find_element_by_xpath("//*[contains(text(), 'Contact:')]//following-sibling::text()[1]")
但是我得到的错误是:
Message: invalid selector: The result of the xpath expression "//*[contains(text(), 'Contact:')]//following-sibling::text()[1]" is: [object Text]. It should be an element.
答:
1赞
KunduK
12/24/2019
#1
要提取使用和Garmendia, Diane
javascripts executor
childNodes
诱导 () 并等待 (),如下所示WebDriverWait
element_to_be_clickable
XPATH
法典:
element=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//p[contains(.,'Contact:')]")))
print(driver.execute_script('return arguments[0].childNodes[1].textContent;', element))
评论
0赞
Jawad Ahmad Khan
12/24/2019
那行得通,你能指导我怎样才能得到P:(PHONE)吗?
0赞
Jawad Ahmad Khan
12/24/2019
它们可以位于任意位置,因此不能使用 childNodes[1]。
0赞
KunduK
12/24/2019
这是你应该得到它的方式。要获取电话号码,您可以尝试print(driver.execute_script('return arguments[0].childNodes[10].textContent;', element))
1赞
KunduK
12/24/2019
最好的方法是用美丽的汤来获得这个。如果你愿意,我也可以发布这个答案。
0赞
Jawad Ahmad Khan
12/24/2019
没关系,我知道美丽的汤。!
评论