python基于控制浏览器爬虫

本文通过实例演示了如何使用Selenium进行网页自动化测试,包括创建Chrome浏览器对象、隐性等待、窗口最大化、发送请求获取页面、使用XPath定位元素、输入搜索内容、模拟点击操作、获取并打印元素属性、模拟鼠标双击等关键步骤。

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

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import time

#创建浏览器对象
d = webdriver.Chrome()#可以看到浏览器界面
d.implicitly_wait(10)#隐性等待10秒如果10秒内该窗口完成渲染渲染完毕就不再等待,10秒还未渲染成功就不再等待


# from selenium.webdriver.chrome.options import Options
# chrome_options = Options()
# chrome_options.add_argument('--headless')
# chrome_options.add_argument('--disable-gpu')
# d = webdriver.Chrome(chrome_options=chrome_options)#创建浏览器界面但是不显示界面

d.maximize_window()#窗口最大化
url = 'https://www.baidu.com'
d.get(url)#发送请求获取界面

node = d.find_element_by_xpath('//*[@id="kw"]')#根据xpath进行获取对象(百度搜索框)

butten = d.find_element_by_xpath('//*[@id="su"]')#获取到按钮对象

node.send_keys('吴秀波')#向搜索框添加搜索内容

su = butten.click()#模拟点击搜索按钮

print(d.window_handles)#输出打开的窗口
d.switch_to.window(d.window_handles[0])#跳转`窗口



#find_elements_by_xpath获取的是列表,不能直接使用必须取出
node1 = d.find_elements_by_xpath('//*[@id="1"]/h3/a')
print(type(node1[0]))
#输出node1的href属性
print(node1[0].get_attribute('href'))

#模拟鼠标点击该控件
time.sleep(3)
ActionChains(d).move_to_element(node1[0]).double_click().perform()


time.sleep(1)
d.close()
d.quit()










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值