# coding=utf-8
from selenium import webdriver
from lxml import etree
import time
class spdier(object):
def __init__(self):
self.driver=webdriver.Chrome(executable_path="D:\software\chromedriver_win32\chromedriver.exe")
def run(self,url):
self.driver.get(url)
input_kw =self.driver.find_element_by_id("kw").send_keys("python")
btn_sure=self.driver.find_element_by_id('su')
btn_sure.click()
time.sleep(2)
f=open("./html.txt","w",encoding="utf-8")
f.write(self.driver.page_source)
html=etree.HTML(self.driver.page_source)
xpath_html=html.xpath("//div[@class='result c-container ']")
title=self.driver.title
url=self.driver.current_url
if __name__ == '__main__':
spi=spdier()
spi.run("http://www.baidu.com")
总结:
1 找到input 后设置 使用方法send_keys() 添加文本
2在使用xpath 的时候 记得html.xpath("//div[@class=’ ']") 使用属性的时候 记得加 @
3在获取源码的时候 需要等待几秒钟 如果有js 动态渲染的话 页面的 代码是不完整的。
4selenium的方法 get(url) 找到控件的方法
上新了:
1 selenium 中 出现异常 该怎么办
首先需要导入 模块 该模块中很多错误类型 自行选择
from selenium.common.exceptions import TimeoutException, NoSuchElementException
def run(self, url):
try:
self.driver.get(url)
except TimeoutException:
print("连接超时")
self.driver.implicitly_wait(2)
try:
input_kw = self.driver.find_element_by_id("kw").send_keys("python")
except NoSuchElementException:
print("DOM 中没有该元素")
2 显式等待 和 隐式等待
显示等待
直接 time.sleep(3) 粗暴 弊端就不说了
还有
self.driver.get(url)
self.driver.implicitly_wait(2)
隐式等待 知道element 出现 或者满足条件继续执行 导入模块
#敲黑板
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait #等待
from selenium.webdriver.support import expected_conditions as EC #等待满足的条件
from selenium.webdriver.common.by import By
class spdier(object):
def __init__(self):
self.driver = webdriver.Chrome(executable_path="D:\software\chromedriver_win32\chromedriver.exe")
def run(self, url):
try:
self.driver.get(url)
except TimeoutException:
print("")
self.driver.implicitly_wait(2)
try:
input_kw = self.driver.find_element_by_id("kw").send_keys("python")
except NoSuchElementException:
print("")
# 超时 5s
wait = WebDriverWait(self.driver, 5)
# 设置一个获取元素的方式
locator= (By.XPATH, '//div[@id="page"]/a[1]')
# 限定的条件 EC中不同的方法 传递的locator 是不一样的
elent = EC.presence_of_element_located(locator)
#elent 是一个可执行的方法 直到DOM中有locator 就执行 下面的
element = wait.until(elent)
#WebDriverWait(self.driver,5).until(EC.presence_of_element_located(By.XPATH,"//div[@id='page']/a[1]")).click()
element.click()