简体   繁体   English

如何使用Selenium和Python更改DOM中的属性值

[英]How can I change an attribute value in the DOM using Selenium and Python

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

<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>

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. 上面的HTML代码在网站上用于显示我要抓取的数据表中的行数。 The total size of the table is just over 300 rows. 该表的总大小刚好超过300行。

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. 我使用Selenium选择其中一个选项没有问题,但是我希望实现的是操纵DOM并将最后一个值从100更改为350,这样当我的脚本选择该选项时,整个表就显示出来,而无需我通过分页进行迭代。

I've read that I can use execute_script, but I don't know how to change the values of one of the options. 我已经读到可以使用execute_script,但是我不知道如何更改选项之一的值。 For example: 例如:

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

Any help would be most appreciated. 非常感激任何的帮助。

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. 可能仍将值限制为100,依此类推。

The Javascript part just takes the element you passed it and sets the value to whatever you pass in, eg "300". Javascript部分只接受您传递它的元素,并将值设置为您传递的任何值,例如“ 300”。

select = driver.find_element_by_id("uniqueid")
WebDriver.execute_script("arguments[0].value = arguments[1]", select, "300")
dimension = image.size['width'] * image.size['height']
driver.execute_script('arguments[0].setAttribute("dimension","{}");'.format(dimension), image)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM