selenium详细讲解

本文深入讲解了Selenium在Python中的应用,包括截屏、获取页面信息如cookies和URL,以及查找页面元素的各种方法,如通过ID、class属性、XPath等。此外,还介绍了页面操作如前进、后退,以及如何在登录网站后利用cookies进行请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、截屏与获取

1.截屏

1.导入包,定位搜索框并输入内容,定位搜索按钮并点击

from selenium import webdriver
import time
chrome = webdriver.Chrome()
chrome.maximize_window()

chrome.get('https://www.baidu.com')

chrome.find_element_by_id('kw').send_keys('孙兴华B站')

chrome.find_element_by_id('su').click()

2.截取屏幕

time.sleep(2)
chrome.save_screenshot('e:/11.png')

2.获取

2.1获取cookies值

#获取当前页面的cookies值
print(chrome.get_cookie)

2.2获取当前页面返回代码

#拿到检查后的代码
print(chrome.page_source) 

2.3获取当前页面url

#获取当前页面的url
print(chrome.current_url)

二、查找元素

1.网页中套着另一个网页【豆瓣】

from selenium import webdriver

chrome = webdriver.Chrome()
chrome.maximize_window()
chrome.get('https://www.douban.com/')

#定位iframe【网页中含有网页】
iframe_u = chrome.find_element_by_tag_name('iframe')

#切换iframe子网页
chrome.switch_to.frame(iframe_u)

#定位元素(密码登录)
p_denglu = chrome.find_element_by_xpath('//li[text()="密码登录"]')
p_denglu.click()

2.通过标签的ID获取标签【重点】

密码 = 浏览器对象.find_element_by_id('password')
print(密码)
#<selenium.webdriver.remote.webelement.WebElement (session="20768af2ef9dd72840825ca1f7f98153", element="76e5f40d-69c2-406f-9c99-f8477754c692")>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值