# !/usr/bin/env python
# -*- coding:utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
# 定义浏览器
browser = webdriver.Chrome()
# 本来是下面的因为后面很多地方会用到所以提在前面来
wait = WebDriverWait(browser, 10)
def search():
try:
browser.get("https://www.jd.com")
input= wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, "#key")) )
submit = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#search > div > div.form > button")))
input.clear()
input.send_keys('美食')
submit.click()
# 获取总页数
total =wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#J_bottomPage > span.p-skip > em:nth-child(1) > b")))
return total.text
# 引入这个错误判断时间是因为超出时间默认抛出TimeoutExcrption
except TimeoutException:
# 如果出现错误重新请求一次
return search()
def main():
total = search()
print(total)
if __name__ == '__main__':
main()