问题描述:

I am trying to run Selenium on a local HTML string but can't seem to find any documentation on how to do so. I retrieve HTML source from an e-mail API, so Selenium won't be able to parse it directly. Is there anyway to alter the following so that it would read the HTML string below:

Python Code for remote access:

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()

driver.get("http://www.python.org")

assert "Python" in driver.title

elem = driver.find_element_by_class_name("q")

Local HTML Code:

s = "<body>

<p>This is a test</p>

<p class="q">This is a second test</p>

</body>"

网友答案:

If I understand the question correctly, I can imagine 2 ways to do this:

  1. Save HTML code as file, and load it as url file:///file/location. The problem with that is that location of file and how file is loaded by a browser may differ for various OSs / browsers. But implementation is very simple on the other hand.
  2. Another option is to inject your code onto some page, and then work with it as a regular dynamic HTML. I think this is more reliable, but also more work. This page has a good example.
网友答案:

If I am reading correctly you are simply trying to get text from an element. If that is the case then the following bit should fit your needs:

    elem = driver.find_element_by_class_name("q").text
    print elem

Assuming "q" is the element you need.

网友答案:

Here was my solution for doing basic generated tests without having to make lots of temporary local files.

import json
from selenium import webdriver
driver = webdriver.PhantomJS()  # or your browser of choice

html = '''<div>Some HTML</div>'''
driver.execute_script("document.write('{}')".format(json.dumps(html)))
# your tests
相关阅读:
Top