from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from urllib.parse import quote
from pyquery import PyQuery as pq
import pymongo
browser=webdriver.Chrome()
wait=WebDriverWait(browser,10)
KEYWORD='iPad'
def index_page(page):
print('正在爬取第{}页'.format(page))
try:
url='https://s.taobao.com/search?q='+quote(KEYWORD)
browser.get(url)
if page>1:
input=wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR,'input.J_Input')))
submit=browser.find_element_by_css_selector('.inner.clearfix div.form span.btn.J_Submit')
input.clear()
input.send_keys(page)
submit.click()
wait.until(
EC.text_to_be_present_in_element((By.CSS_SELECTOR,'.item.active'),
str(page)))
wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR,'.item.J_MouserOnverReq ')))
get_products()
except TimeoutException:
index_page(page)
def get_products():
html=browser.page_source
doc=pq(html)
items=doc('.item.J_MouserOnverReq ').items()
for item in items:
product={
'image':'https:'+item.find('.J_ItemPic.img').attr('data-src'),
'price':item.find('.price.g_price.g_price-highlight').text(),
'deal':item.find('.deal-cnt').text(),
'title':item.find('.row.row-2.title').text(),
'shop':item.find('.shopname').text(),
'location':item.find('.location').text(),
}
print(product)
save_to_mongo(product)
MONGO_URL='localhost'
MONGO_DB='test'
MONGO_COLLECTION="products"
client=pymongo.MongoClient(MONGO_URL)
db=client[MONGO_DB]
def save_to_mongo(result):
try:
if db[MONGO_COLLECTION].insert(result):
print('成功存储到MongoDB')
except Exception:
print('Failed!')
MAX_PAGE=100
def main():
for i in range(MAX_PAGE):
index_page(i+1)
main()