encoding=utf8
import re
from pyquery import PyQuery as pq
from selenium import webdriver
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('C:\Program Files (x86)\Google\Chrome\Application/chromedriver.exe')
wait=WebDriverWait(browser, 10)
def search():
try:
browser.get('https://www.taobao.com')
#獲取并設(shè)置搜索框
input = wait.until(
#加載成功
EC.presence_of_element_located((By.CSS_SELECTOR, "#q"))
)
#獲取并設(shè)置點擊按鈕
submit = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#J_TSearchForm > div.search-button > button")))
#模擬給搜索框一個關(guān)鍵字
input.send_keys('美食'.decode('utf8'))
#模擬點擊按鈕
submit.click()
totalpage = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.total"))
)
get_product()
return totalpage.text
except Exception, e:
return search()
def next_page(page_number):
try:
# 獲取并設(shè)置搜索框
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > input"))
)
# 獲取并設(shè)置點擊按鈕
submit = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit")))
# 模擬給搜索框一個關(guān)鍵字
input.clear()
input.send_keys(page_number)
# 模擬點擊按鈕
submit.click()
wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li:nth-child(3) > a'),str(page_number)))
get_product()
except Exception, e:
return search()
def main():
totalpage=search()
totalpage=int(re.compile('(\d+)').search(totalpage).group(1))
for i in range(2,totalpage+1):
next_page(i)
def get_product():
# 加載成功
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-itemlist .items .item")))
html=browser.page_source
#print type(html)
doc=pq(html)
#print doc
#items()可以獲取所有被選中的內(nèi)容
items=doc('#mainsrp-itemlist .items .item').items()
for item in items:
product={
'image':item.find('.pic .img').attr('src')
}
print product
if name =='main':
main()