import time
from selenium import webdriver
from selenium.webdriver.common.by import By
# 显式等待库
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
# 调获取chrome用浏览器
browser = webdriver.Chrome()
# 打开指定网址
browser.get('http://www.taobao.com')
# 获取页面源码
time.sleep(10)
# 执行js往下执行
browser.execute_script('window.scrollTo(0, 1000)')
time.sleep(10)
html = browser.page_source
print(html)
# 解析页面源码可使用beautifulsoup(html), lxml.etree.HTML(html)
# pyquery(html)
good1 = browser.find_element_by_css_selector('#dg-item-tl-0')
good2 = browser.find_element_by_xpath('//*[@id="dg-item-tl-0"]')
good3 = browser.find_element_by_id('dg-item-tl-0')
good4 = browser.find_element(By.ID,'dg-item-tl-0')
print(good1.text)
print(good2.text)
print(good3.text)
print(good4.text)
# 关闭浏览器
browser.close()
# 前进后退
broswer = webdriver.Chrome()
broswer.get('https://www.baidu.com')
broswer.get('https://www.taobao.com')
broswer.get('https://www.zhihu.com')
# 回退一步
broswer.back()
# 前进一步
broswer.forward()
# 等待
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
# 隐式等待
#
# 默认情况下等待时长为0
# implicitly_wait(10)比time.sleep(10)更加智能,time.sleep(10)必须等待十秒,如果已经加载出来还要等待满10秒
browser.implicitly_wait(10)
browser.execute_script('window.scrollTo(0, 1000)')
good2 = browser.find_element_by_xpath('//*[@id="dg-item-tl-0"]')
print(good2)
browser.close()
# 显示等待
# 等待元素是否被加载出来,还可以判断加载的元素是否有点击效果,是否等于某些值...
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
wait = WebDriverWait(browser, 10)
browser.execute_script('window.scrollTo(0, 1000)')
good6 = wait.until(
# 等待元素被加载
EC.presence_of_all_elements_located((By.CSS_SELECTOR, '#dg-item-tl-0'))
)
button = wait.until(
# 等待元素被加载,且具有click效果
EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_SearchTab > ul > li.J_SearchTab.selected.goods-search-tab'))
)
print(good6)
browser.close()
# 打开jd,并输入内容实现点击
browser = webdriver.Chrome()
browser.get('http://www.1234567.com.cn')
# 显式等待
wait = WebDriverWait(browser, 10)
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, '#search-input'))
)
button = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, '#searchbar > div > div.searchbar-form.search-left > form > div.searchbar-btn.search-left > button'))
)
# 清空输入框
input.clear()
# 输入内容
input.send_keys('招商白酒')
# 点击搜索
button.click()
time.sleep(10)
button1 = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, '#addSel'))
)
button1.click()
网友评论