博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python使用Selenium爬取淘宝异步加载的数据方法
阅读量:2069 次
发布时间:2019-04-29

本文共 3787 字,大约阅读时间需要 12 分钟。

淘宝的页面很复杂,如果使用分析ajax或者js的方式,很麻烦

抓取淘宝‘美食'上面的所有食品信息

spider.py

import refrom selenium import webdriverfrom selenium.common.exceptions import TimeoutExceptionfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom bs4 import BeautifulSoupfrom config import *import pymongo'''想要学习Python?Python学习交流群:973783996满足你的需求,资料都已经上传群文件,可以自行下载!'''client=pymongo.MongoClient(MONGODB_URL)db=client[MONGODB_DB]  ##这里使用PhantomJS,并配置了一些参数browser=webdriver.PhantomJS(service_args=SERVICE_ArGS) ##窗口的大小,不设置的话,默认太小,会有问题browser.set_window_size(1400,900) wait=WebDriverWait(browser, 10)  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'))      )     ######这块python2搞得鬼    #input.send_keys('\u7f8e\u98df'.decode("unicode-escape"))    input.send_keys(KEYWORD.decode("unicode-escape"))    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('翻页'+str(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:    return next_page(page_number) #获取产品信息def get_product():  products = wait.until(    EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-itemlist .m-itemlist .items'))        )##拿到网页  html = browser.page_source  soup = BeautifulSoup(html,'lxml')  items = soup.select('#mainsrp-itemlist .m-itemlist .items .item.J_MouserOnverReq')#   print('*************************到此*************')  for item in items:    img = item.select('.J_ItemPic.img')[0].get('src')    price = item.select('.price.g_price.g_price-highlight > strong')[0].get_text()    deal = item.select('.deal-cnt')[0].get_text()    title= item.select('.row.row-2.title > a ')[0].get_text().strip() #:nth-of-type(3)    shop = item.select('.row.row-3.g-clearfix > .shop > a > span:nth-of-type(2)')[0].get_text()     location = item.select('.location')[0].get_text()     product={      'img':img,      'price':price,      'deal':deal,      'title':title,      'shop':shop,      'location':location    } #打印一下    import json    j = json.dumps(product)    dict2 = j.decode("unicode-escape")    print dict2     save_to_mongo(product)  def save_to_mongo(product):  try:    if db[MONGODB_TABLE].insert(product):      print('存储到mongodb成功'+str(product))  except Exception:    print("存储到mongodb失败"+str(product))   def main():   try:    total=search()     ##搜寻 re正则表达式    s=re.compile('(\d+)')    total=int(s.search(total).group(1))    for i in range(2,total+1):      next_page(i)  except Exception:    print('出错')  finally:    browser.close() if __name__ == '__main__':  main()

config.py

MONGODB_URL='localhost'MONGODB_DB='taobao'MONGODB_TABLE='meishi' SERVICE_ArGS=['--load-images=false','--disk-cache=true'] ##就是美食这两个字,直接用汉字会报错KEYWORD='\u7f8e\u98df'

以上这篇Python使用Selenium爬取淘宝异步加载的数据方法就是小编分享给大家的全部内容了,希望能给大家一个参考

转载地址:http://ysnmf.baihongyu.com/

你可能感兴趣的文章
Linux vi/vim编辑器常用命令与用法总结
查看>>
如何使用Git Bash Here,将本地项目传到github上
查看>>
eclipse git控件操作 回退到历史提交 重置 删除(撤销)历史的某次提交
查看>>
Oracle | 给表和字段添加注释
查看>>
java比较日期大小及日期与字符串的转换【SimpleDateFormat操作实例】
查看>>
Oracle新表使用序列(sequence)作为插入值,初始值不是第一个,oraclesequence
查看>>
java中System.exit()方法
查看>>
在hbase shell中过滤器的简单使用
查看>>
java静态方法和实例方法
查看>>
java多线程并发去调用一个类的静态方法,会有问题吗?
查看>>
关于JAVA中的static方法、并发问题以及JAVA运行时内存模型
查看>>
Java命令学习系列(一)——Jps
查看>>
java如何计算程序运行时间
查看>>
Java Calendar 类的时间操作
查看>>
Java]NIO:使用Channel、Charset(字符集)、使用Charset传递CharBuffer
查看>>
Eclipse下运行Maven项目提示缺少maven-resources-plugin:2.4.3
查看>>
Java 中int、String的类型转换
查看>>
比较两个JSON字符串是否完全相等
查看>>
删除JSONArray中的某个元素
查看>>
Linux下Tomcat重新启动
查看>>