selenium入门

1. 安装selenium库

pip install selenium

2. 下载chromedriver

Chromedriver

查看自己chrome的型号下载相应的chromedriver
Customize and control Google Chrome -> Help -> About Google Chrome

下载到目标文件夹后解压

3. 安装ipython

pip install ipython

4. 简单脚本编写

from selenium.webdriver import Chrome #注意Chrome的C是大写的
driver = Chrome(executable_path=r"C:\Users\zhou\Desktop\chrome\chromedriver.exe")
driver.get('https://www.baidu.com/')
input_box=driver.find_element_by_xpath("//*[@id="kw"]")
input_box.send_keys("易烊千玺")
# click_button = driver.find_element_by_xpath("//input[@id="su"]")
# click_button.click()
sub_text=driver.find_elements_by_xpath('//table[@class="new-inc-rs-table"]/descendant::a')  
for text in sub_text:
	print(text.text)
result:
千玺说大学要谈一场恋爱
易烊千玺送你一朵小红花图片
王俊凯真实身高
易烊千玺个人资料及简介
易烊千玺微博
易烊千玺为什么越长越帅
tfboys为什么不能互提
易烊千玺恋情
王源真实身高

当加载页面很慢时,selenium可能不会等页面加载完成就自动退出了,可以用explicit waits或implicit waits解决

Explicit waits

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebdriverWait
from selenium.webdriver.support import expected_conditions as EC

xpath_selector='//a[text()="Pacakages"]'
wait_ele = WebDriverWait(driver,10).until(EC.presence_of_element_located(By.XPATH,xpath_selector))

Implicit waits

driver.implicit_wait(10)

隐藏浏览器

from selenium.webdriver import ChromeOptions
options=ChromeOptions()
options.headless=True
driver = Chrome(executable_path=r"C:\Users\zhou\Desktop\chrome\chromedriver.exe",option=options)

后退、退出

driver.back()
driver.quit()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值