selenium的各种操作

import time

from selenium.webdriver import Edge
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys  # 键盘输入

# 1.创建浏览器对象
web = Edge()
# 2.打开一个网址
web.get("https://lagou.com")

# 找到某个元素,点击它
el = web.find_element(By.XPATH, '//*[@id="changeCityBox"]/ul/li[1]/a')
el.click()  # 点击事件

time.sleep(1)  # 让浏览器缓一会,等他加载出来
#  巨坑:selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
#  字面上的意思是,引用的元素已过时。原因是页面刷新了,此时当然找不到之前页面的元素,就算是后退回来的页面也是不一样的。
# 也就是太快了,还没响应回来就去找就会导致上面的报错,所以要等一下


# 找到输入框 输入python 输入回车/点击搜索按钮
web.find_element(By.XPATH, '//*[@id="search_input"]').send_keys('python', Keys.ENTER)

time.sleep(1)  # 让浏览器缓一会,等他加载出来
# 找到页面中所有的div,查找存放数据的位置,进行数据提取
# find_elements加了个s 提取多个
div_list = web.find_elements(By.XPATH, '//*[@class="list__YibNq"]/div')

for div in div_list:
    job_name = div.find_element(By.XPATH, './/*[@id="openWinPostion"]').text
    job_wages = div.find_element(By.XPATH, './/*[@class="money__3Lkgq"]').text
    print(job_name, job_wages)
posted @ 2023-03-05 19:53  0x1e61  阅读(19)  评论(0编辑  收藏  举报