Python selenium - 修改网页的源代码

时间:2016-09-17 05:39:09

标签: python selenium

我正在使用Python selenium自动化我的出勤录入。它工作正常,现在我想尝试修改源代码。我看过几篇帖子说明可以使用driver.execute_script()修改它,它适用于JavaScript,但在我的情况下,我需要修改select标记下的源代码。我能够使用inspect element修改源代码。以下是select标签源代码:

<select name="date1">
    <option value="2016-09-17">2016-09-17</option>
    <option value="2016-09-16">2016-09-16</option>
    <option value="2016-09-14">2016-09-14</option>
</select>

我尝试用driver.execute_script()做到这一点。以下是我的代码:

sel = driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/form/table/tbody/tr[2]/td[3]/select')
input_list = sel.find_element_by_tag_name('option')
cmd = "input_list.value = '2016-09-07'"
driver.execute_script(cmd)

但上面的代码给出了以下错误:

  

selenium.common.exceptions.WebDriverException:消息:input_list未定义

我可以使用inspect element窗口修改源代码。有没有办法用selenium修改源代码?

3 个答案:

答案 0 :(得分:2)

问题是execute_script在浏览器[1]中执行JavaScript,它对python脚本中的python变量一无所知。特别是input_list没有为JavaScript定义,因为它是一个python变量。

要解决此问题,您可以选择JavaScript文件中的元素。为此,您可以将cmd设置为类似[2]:

    function getElementByXpath(path) {
      return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    }

    getElementByXpath("/html/body/div[3]/div/div[2]/form/table/tbody/tr[2]/td[3]/select/option[1]").value = '2016-09-07';
<html>
  <body>
    <div></div>
    <div></div>
    <div>
      <div>
        <div></div>
        <div>
          <form>
            <table>
              <tbody>
                <tr></tr>
                <tr>
                  <td></td>
                  <td></td>
                  <td>
                    <select name="date1">
                      <option value="2016-09-17">2016-09-17</option>
                      <option value="2016-09-16">2016-09-16</option>
                      <option value="2016-09-14">2016-09-14</option>
                    </select>
                  </td>
                </tr>
              </tbody>
            </table>
          </form>
        </div>
      </div>
    </div>
    

[1] https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script

[2] Is there a way to get element by Xpath using JavaScript in Selenium WebDriver?

答案 1 :(得分:2)

尝试以下解决方案,如果出现任何问题,请与我们联系:

driver.execute_script("""document.querySelector("select[name='date1'] option").value="2016-09-07";""")

P.S。我建议你不要在你的选择器中使用绝对XPath,而是相对而言

答案 2 :(得分:0)

python 中使用:

element = driver.find_element_by_id("some-random-number")
driver.execute_script("arguments[0].innerText = 'change text'", element)