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')
#获取并设置搜索框
input = wait.until(
#加载成功
EC.presence_of_element_located((By.CSS_SELECTOR, "#q"))
)
#获取并设置点击按钮
submit = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#J_TSearchForm > div.search-button > button")))
#模拟给搜索框一个关键字
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:
# 获取并设置搜索框
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > input"))
)
# 获取并设置点击按钮
submit = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit")))
# 模拟给搜索框一个关键字
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()可以获取所有被选中的内容
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()