Python 中的 Selenium - 运行 JavaScript [英] Selenium in Python - Running JavaScript

查看:18
本文介绍了Python 中的 Selenium - 运行 JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试抓取一个主要由 javascript 运行的网站,这让我很头疼,因为我不懂 javascript.

I'm trying to scrape a website that is mainly ran by javascript and it's giving me a huge headache because I don't know javascript.

这是我目前所拥有的:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.keys import Keys

binary = FirefoxBinary(r'C:\Users\kwright\AppData\Local\Mozilla Firefox\firefox.exe')

driver = webdriver.Firefox(firefox_binary=binary)
driver.get('http://www.papowerswitch.com/shop-for-electricity/shop-for-your-home')
#zipcode = driver.find_element_by_id('edit-zipcode')
monthlyuse = driver.find_element_by_name('estimated-monthly-usage')
button = driver.find_element_by_id("edit-submit-residential-rate-search2")
driver.execute_script("document.getElementById('edit-zipcode').value='18707'")

这很好用,它为我提供了邮政编码部分所需的值.下一部分我遇到了麻烦,因为 Id 名称不是唯一的,但名称标签是,我的问题是我不知道通过名称标签获取元素并输入我需要的数据的 javascript 函数.

This works fine and it give me the value I need in the zip code section. The next part I'm having trouble with because the Id names aren't unique, but the name tag is, my problem is that I don't know the javascript function to get the element by the name tag and input the data I need.

我尝试了这个和这个的几个变体,但没有奏效.

I tried this and several variations of this and it didn't work.

driver.execute_script("driver.findElement(webdriver.By.name('estimated-monthly-usage')).value='1000'")

任何人都可以在这里帮助我,让我知道我需要添加什么脚本来填写表格的那部分?谢谢你.

can anyone help me out here and let me know what script I need to add to get that part of the form filled out? Thank you.

这是 HTML每月使用量

Here is the HTML Monthly Usage

推荐答案

driver.findElementSelenium 语法,而在 driver.execute_script 内部您需要 JavaScript 语法:

driver.findElement is Selenium syntax, while inside driver.execute_script you need JavaScript syntax:

driver.execute_script("some javascript code comes here");

要找到合适的函数,查看文档DOM对象:就像document.getElementById,你之前用过的,它有 document.getElementsByName() 函数.请注意,与 ID 只能返回 1 个元素不同,可以有许多具有相同名称的元素,因此函数将它们全部作为数组返回.所以你的陈述变成了:

To find the right function, look at document DOM object: just like document.getElementById, which you previously used, it has document.getElementsByName() function. Note that unlike ID, that can return 1 element only, there can be many elements with the same name, hence function returns them all as an array. So your statement becomes:

driver.execute_script("document.getElementsByName('estimated-monthly-usage')[0].value='1000'");

这篇关于Python 中的 Selenium - 运行 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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