selenium+phantomjs+pyquery 爬取淘宝商品信息

 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
import re
from pyquery import PyQuery as pq
from config import *
import pymongo client = pymongo.MongoClient(MONGO_URL)
db =client[MONGO_DB] browser = webdriver.PhantomJS(service_args=SERVICE_ARGS)
wait = WebDriverWait(browser, 10)# 等待时长10秒,默认0.5秒询问一次,等待页面加载完成,找到某个条件发生后再继续执行后续代码,如果超过设置时间检测不到则抛出异常
browser.set_window_size(1400,900)
def search():
print("正在搜索")
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('美食')#添加input
submit.click()#模拟按下搜索按钮
total=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.total")))
get_product()
return total.text
except TimeoutException:
return search()
def next_page(page_number):#翻页,把当前页码清除后,直接跳转到想去的页码
print("正在翻页",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.item.active > span"),str(page_number)))
get_product()
except TimeoutException:
next_page(page_number)
def get_product():#获得每页商品内容,pyquery not understand
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-itemlist .items .item")))
html =browser.page_source
# print(html)
doc = pq(html)
items = doc("#mainsrp-itemlist .items .item").items()#注意class名字后空格!
for item in items:
product = {
'image':item.find('.pic .img').attr('src'),
'price':item.find('.price').text(),
'deal':item.find('.deal-cnt').text()[:-3],
'title':item.find('.title').text(),
'shop':item.find('.shop').text(),
'location':item.find('.location').text()#find 查找的是div class的名字 别的标签不可以
}
print(product)
save_to_mongo(product)
def save_to_mongo(result):#将数据存储到mongodb
try:
if db[MONGO_TABLE].insert(result):
print('存储成功->',result)
except Exception:
print('存储失败->',result)
def main():
total = search()
total = int(re.compile('\d+').search(total).group(0))
for i in range(2,20):
next_page(i)
browser.close() if __name__ == '__main__':
main()

MONGO_URL = 'localhost'
MONGO_DB = 'taobao'
MONGO_TABLE = 'product' SERVICE_ARGS = ['--load-images=false', '--disk-cache=true']

config


上一篇:Office 365邮件自动转发管理设置


下一篇:王者荣耀英雄全皮肤4K高清大图,python爬虫帮你保存下来