1、用selenium自动爬取淘宝美食的商品信息,先定义search方法,该方法用来在搜索框中输入“美食”,然后点击搜索按钮。浏览器加载需要时间,要判断浏览器加载成功再执行下一步的操作,其使用方法可在python-selenium官网查看waits相关的介绍,部分代码复制粘贴即可。设置的条件要在指定的时间内加载出来,否则会抛出异常,使用try回归这个方法。
Input为搜索框,submit为搜索按钮,判断完成后搜索框中输入“美食”,然后点击搜索按钮,最后main方法调用。
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser=webdriver.Chrome()
def search():
try:
browser.get("https://www.taobao.com")
input = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#q")))
submit = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#J_TSearchForm > div.search-button > button")))
input.send_keys("美食"