Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

html - How do I obtain the text in a <p> tag contained by an iframe using Selenium with Python?

A block of code, from the webpage I'm working on looks like the following -

<div class="A">
  <iframe id="frameA">
    #document
      <html style>
        <head></head>
        <body style>
          <p style>Random Text Goes Here</p>
        </body>
      </html>
  </iframe>
</div>

I would like to extract the text in the paragraph tag, "Random Text Goes Here". However, many articles on the internet suggest that iframes cannot be identified directly using an XPath or a CSS Selector like divs and spans are, using their classes or ids. I've experienced the same, upon trying this piece of code -

exem = driver.find_element_by_tag_name("frameA")
driver.switch_to.frame(exem)
required_field = driver.find_element_by_xpath("html/body/p").text
print(required_field) 

I'm not sure if the aforementioned code is even right, but I've just tried doing this on the basis of things I've understood from some online sources. This fails to find the paragraph in the iframe, i.e. a NoSuchElementException is raised.

Can someone help me out with this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
driver.find_element_by_tag_name("frameA")

FrameA is id not tag , change locator to iframe

driver.find_element_by_tag_name("iframe")

Or

driver.find_element_by_id("frameA")

Note:

driver.switch_to_frame or driver.switch_to.frame both support frame_name . Eg

driver.switch_to.frame("frameSOmething") but as the iframe doesn't have any attribute 'name' in your case . You can use only above mentioned methods


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...