如何使用Selenium和Python更改DOM中的属性值 [英] How can I change an attribute value in the DOM using Selenium and Python

查看:460
本文介绍了如何使用Selenium和Python更改DOM中的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python和Selenium浏览网站,但遇到一个我不知道如何解决的问题(假设甚至有可能!)

I'm trying to navigate through a website using Python and Selenium and I've run into an issue that I can't figure out how to solve (assuming it's even possible!)

<select id="uniqueid" autocomplete="off" value="10">
  <option selected="selected" value="10">10</option>
  <option value="30">30</option>
  <option value="50">50</option>
  <option value="100">100</option>
</select>

上面的HTML代码在网站上用于显示我要抓取的数据表中的行数.该表的总大小刚好超过300行.

The above HTML code is used on the site for displaying the number of rows in a table of data which I'm trying to scrape. The total size of the table is just over 300 rows.

我使用Selenium选择一个选项没有问题,但是我希望实现的是操纵DOM并将最后一个值从100更改为350,这样当我的脚本选择该选项时,整个表格就会显示出来无需我遍历分页.

I've had no problem selecting one of the options using Selenium but what I was hoping to achieve was to manipulate the DOM and change the last value from 100 to 350 so that when my script selects that option the entire table is displayed without me having to iterate through the pagination.

我已经阅读到可以使用execute_script,但是我不知道如何更改其中一个选项的值.例如:

I've read that I can use execute_script, but I don't know how to change the values of one of the options. For example:

WebDriver.execute_script("document.getElementById('uniqueid') --what text goes here-- = '350')

任何帮助将不胜感激.

推荐答案

您可以尝试执行此操作,但要了解,向您发送任何值都可能使该站点无法正常运行.可能仍会将值限制为100,依此类推.

You can try this but understand that the site may not be OK with you sending whatever for a value. It may still limit the value to 100, etc.

Javascript部分只接受您传递它的元素,并将值设置为您传递的任何内容,例如"300".

The Javascript part just takes the element you passed it and sets the value to whatever you pass in, e.g. "300".

select = driver.find_element_by_id("uniqueid")
WebDriver.execute_script("arguments[0].value = arguments[1]", select, "300")

这篇关于如何使用Selenium和Python更改DOM中的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆