使用Selenium模拟浏览器抓取淘宝商品美食信息

发表于:2018-4-12 10:13

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:脚本_驱动    来源:博客园

  学习目的:
  selenium目前版本已经到了3代目,你想加薪,就跟面试官扯这个,你赢了,工资就到位了,加上一个脚本的应用,结局你懂的
  正式步骤
  需求背景:抓取淘宝美食
  Step1:流程分析
  搜索关键字:利用selenium驱动浏览器搜索关键字,得到查询后的商品列表
  分析页码并翻页:得到商品页码数,模拟翻页,得到后续页面的商品列表
  分析提取商品内容:利用PyQuery分析源码,解析得到商品列表
  存储至MongoDB:将商品列表信息存储到数据库MongoDB
  Step2:代码分析
  chromedriver 下载:http://chromedriver.storage.googleapis.com/index.html
# -*-  coding:utf-8 -*-
import re
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
from selenium.common.exceptions import TimeoutException
import time
from pyquery import PyQuery as pq
from config_taobao import *
import pymongo
###数据库设置###
client = pymongo.MongoClient(MONGO_URL)
#client后的数据库用[]
db = client[MONGO_DB]
#公共参数
driver = webdriver.Chrome()
url = 'https://www.taobao.com'
wait = WebDriverWait(driver, 10)
def search():
driver.get(url)
#显式等待参考了官方api文档 http://selenium-python.readthedocs.io/waits.html
searchbox = wait.until(EC.presence_of_element_located((By.ID, "q")))
submit = driver.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button')
#下面是测试代码,验证提交按钮是否可用
submit1 = wait.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="J_TSearchForm"]/div[1]/button')))
#    print(submit1.text)
#搜索关键字可以设置为用户收入,在公共参数表用Python的input函数
searchbox.send_keys('美食')
submit.click()
#等待页面加载出搜索结果的总页数
total = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@class="total"]')))
#页码加载完成后,获取商品信息
get_products()
return total.text
def next_page(page_number):
try:
input = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')))
submit = driver.find_element_by_css_selector('#mainsrp-pager > div > div > div > div.form > span.btn.J_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)
#此处设置等待时间是因为我本地的网速过快,不休眠一下,无法正常点击
time.sleep(3)
submit.click()
time.sleep(3)
#验证输入页页码和高亮页是否匹配
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_products()
#下面的异常抓取是函数递归,点击确定按钮失败后,重新加载此函数
except TimeoutException:
next_page(page_number)
def get_products():
#pyquery的用法,我也不是很了解,后续加强学习,现在知道这么用
wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist .items .item'))
)
html = driver.page_source
doc = pq(html)
items = doc('#mainsrp-itemlist .items .item').items()
for item in items:
product = {
'image':item.find('.pic .img').attr('src'),
'price':item.find('.price').text().strip()[3:],
'name':item.find('.title').text(),
'shopname':item.find('.shop').text()
}
print(product)
save_product_info(product)
##保存信息至MongoDB
def save_product_info(result):
if db[MONGO_Table].insert(result):
print('存储成功')
def main():
total = search()
total = int(re.compile('(\d+)').search(total).group(1))
print(total)
for i in range(2,total+1):
next_page(i)
if __name__ == '__main__':
main()
  配置文件信息:
# -*-  coding:utf-8 -*-
MONGO_URL = 'localhost'
MONGO_DB = 'taobao'
MONGO_Table = 'product'
  学习总结:
  爬虫越来越好玩了,继续学

上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号