首页 > 解决方案 > 如何获得价值在 selenium python 中动态加载的占位符?

问题描述

我试图抓取一个网站,您需要在其中传递地址以获取该地址的坐标。我能够传递地址并在浏览器中显示纬度和经度,但无法检索它。

这是怎么回事。

使用此代码,我得到了浏览器中显示的纬度和经度。

from selenium import webdriver
chrome_path = r"C:\Users\Himanshu Poddar\Desktop\chromedriver.exe"
url = 'https://www.latlong.net/convert-address-to-lat-long.html'
wd = webdriver.Chrome(chrome_path)
wd.get(url)

# Get the input element to which address is to be passed
inputElement = wd.find_element_by_xpath('//input[@placeholder="Type address here to get lat long"]')
# send the address
inputElement.send_keys('Domlur, Bangalore')
# click on get the coordinates button
wd.find_element_by_id('btnfind').click()

现在显示纬度和经度:

在此处输入图像描述

如何获取在输入字段中动态生成的纬度和经度,因此在检查元素中找不到。

纬度和经度的检查元素是

纬度

<div class="col-6 m2">
<label for="lat">Latitude</label>
<input type="text" name="lat" id="lat" placeholder="lat coordinate">
</div>

经度

<div class="col-6 m2">
<label for="lng">Longitude</label>
<input type="text" name="lng" id="lng" placeholder="long coordinate">
</div>

其中不包含显示的经纬度。

编辑:我正在寻找返回 latlong 值的函数,我们可以使用 selenium 的 execute_script 来完成吗

标签: pythonselenium-webdriverweb-scraping

解决方案


您可以使用输入节点的“值”属性获取值,尝试以下代码:

from selenium import webdriver
from time import sleep

wd = webdriver.Chrome('C:\NotBackedUp\chromedriver.exe')
wd.get('https://www.latlong.net/convert-address-to-lat-long.html')
inputElement = wd.find_element_by_xpath('//input[@placeholder="Type address here to get lat long"]')
inputElement.send_keys('Domlur, Bangalore')
wd.find_element_by_id('btnfind').click()

sleep(8)
print(wd.find_element_by_id('lat').get_attribute('value'))
print(wd.find_element_by_id('lng').get_attribute('value'))

您需要做的就是,在获取值之前需要延迟一些时间。我使用了 sleep() 方法,但不推荐使用,您也可以尝试其他一些等待。我希望它有帮助...


推荐阅读