如何用selenium把所有用户可见的text及其坐标保存下来注意只保存非空的 text且 text 不包含换行符
可以使用以下步骤使用 Selenium 将所有可见的文本及其坐标保存下来:
- 导入必要的库:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
- 启动 WebDriver 并打开目标网页:
driver = webdriver.Chrome() # 根据实际情况选择不同的 WebDriver
driver.get('目标网页的URL')
- 获取所有可见文本的元素对象并保存它们的文本及坐标:
elements = driver.find_elements_by_xpath("//*[normalize-space(text())!='']")
texts_and_coordinates = []
for element in elements:
text = element.text.replace('\n', '') # 去除换行符
location = element.location
size = element.size
x = location['x']
y = location['y']
width = size['width']
height = size['height']
texts_and_coordinates.append({'text': text, 'x': x, 'y': y, 'width': width, 'height': height})
- 关闭 WebDriver:
driver.quit()
完整代码如下:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get('目标网页的URL')
elements = driver.find_elements_by_xpath("//*[normalize-space(text())!='']")
texts_and_coordinates = []
for element in elements:
text = element.text.replace('\n', '')
location = element.location
size = element.size
x = location['x']
y = location['y']
width = size['width']
height = size['height']
texts_and_coordinates.append({'text': text, 'x': x, 'y': y, 'width': width, 'height': height})
driver.quit()
for item in texts_and_coordinates:
print(item)
这样,所有可见的非空文本及其坐标将保存在 texts_and_coordinates 列表中,并可以按需进一步处理
原文地址: https://www.cveoy.top/t/topic/irX8 著作权归作者所有。请勿转载和采集!