selenium+phantomjs爬取京东商品信息

今天自己实战写了个爬取京东商品信息,和上一篇的思路一样,附上链接:https://www.cnblogs.com/cany/p/10897618.html

打开 https://www.jd.com/ 首先不需要登陆就可搜索,淘宝不一样,所以淘宝我还没试过。

开启F12 定位一下搜索框和搜索按钮

input = WAIT.until(EC.presence_of_element_located((By.XPATH,'//*[@id="key"]')))
submit = WAIT.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="search"]/div/div[2]/button')))
input.send_keys(goods)
submit.click()

接下来我们要的是按销量排名,那就要点击这个 onclick事件

发现使用click()还是无法进行点击,因为这是个js跳转 所以得用下面代码

submit_js = WAIT.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="J_filter"]/div[1]/div[1]/a[2]')))
browser.execute_script("$(arguments[0]).click()", submit_js)

接下来就还是检测是否加载了下面的元素

开始分析各项 怎么获取里面的数据就不说了

这时候可能爬的不完全,因为京东是动态加载的 需要去模拟一下把页面拉到底部

browser.execute_script("window.scrollTo(0,document.body.scrollHeight)")

按照这样子进行循环遍历,把每一个值添加到goods_data列表里去,但也保证不了可能会出现找不到对象的属性,抛出AttributeError异常,这里已经尝试过了,所以写下这个异常处理!

然后获取完一页就下一页,然后得写个代码来检查是否跳转到指定页面

WAIT.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#J_bottomPage > span.p-num > a.curr'),str(page_num)))

再获取每一页当前页面源码进行解析提取内容,保存到 goods_data 列表中,最后写入xls文件!

Tips:里面sleep 时间视情况而定,太快会导致获取不全,但如果网速快能弥补这一点,目前测试情况来看是这样子的问题!

附上代码:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import xlwt
import time goods = input('请输入你要爬取的商品名称:')
goods_data = []
browser = webdriver.PhantomJS()
WAIT = WebDriverWait(browser,10)
browser.set_window_size(1000,600) def seach(goods):
try:
print('开始自动化爬取京东商品信息......')
browser.get('https://www.jd.com/')
input = WAIT.until(EC.presence_of_element_located((By.XPATH,'//*[@id="key"]')))
submit = WAIT.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="search"]/div/div[2]/button')))
input.send_keys(goods)
submit.click()
submit_js = WAIT.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="J_filter"]/div[1]/div[1]/a[2]')))
browser.execute_script("$(arguments[0]).click()", submit_js)
time.sleep(1)
get_source()
except TimeoutException:
return seach(goods) def get_source():
browser.execute_script("window.scrollTo(0,document.body.scrollHeight)")
time.sleep(1)
WAIT.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#J_goodsList > ul')))
html = browser.page_source
soup = BeautifulSoup(html,'lxml')
save_data(soup) def save_data(soup):
html = soup.find_all(class_='gl-i-wrap')
for item in html:
try:
goods_name = item.find(class_='p-name').find('em').text
goods_link = 'https:' + item.find(class_='p-img').find('a').get('href')
goods_evaluate = item.find(class_='p-commit').text
goods_store = item.find(class_='curr-shop').text
goods_money = item.find(class_='p-price').find('i').text
print(('爬取: ' + goods_name))
goods_data.append([goods_name,goods_link,goods_evaluate,goods_store,goods_money])
except AttributeError:
pass def next_page(page_num):
try:
print('获取下一页数据')
next_btn = WAIT.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#J_bottomPage > span.p-num > a.pn-next')))
next_btn.click()
WAIT.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#J_bottomPage > span.p-num > a.curr'),str(page_num)))
get_source()
except TimeoutException:
browser.refresh()
return next_page(page_num) def save_to_excel():
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
sheet = book.add_sheet(goods, cell_overwrite_ok=True)
sheet.col(0).width = 256 * 80
sheet.col(1).width = 256 * 40
sheet.col(2).width = 256 * 20
sheet.col(3).width = 256 * 25
sheet.col(4).width = 256 * 20
sheet.write(0, 0, '商品名称')
sheet.write(0, 1, '商品链接')
sheet.write(0, 2, '评价人数')
sheet.write(0, 3, '店名')
sheet.write(0, 4, '价格')
for item in goods_data:
n = goods_data.index(item) + 1
sheet.write(n, 0, item[0])
sheet.write(n, 1, item[1])
sheet.write(n, 2, item[2])
sheet.write(n, 3, item[3])
sheet.write(n, 4, item[4])
book.save(str(goods) + u'.xls') def main():
try:
seach(goods)
for i in range(2,11):
next_page(i)
print('-'*50)
print('数据爬取完毕,正在写入xls.....')
save_to_excel()
print('写入成功!!!')
finally:
browser.close()
browser.quit() if __name__ == '__main__':
main()

selenium+phantomjs爬取京东商品信息的更多相关文章

  1. selenium模块使用详解、打码平台使用、xpath使用、使用selenium爬取京东商品信息、scrapy框架介绍与安装

    今日内容概要 selenium的使用 打码平台使用 xpath使用 爬取京东商品信息 scrapy 介绍和安装 内容详细 1.selenium模块的使用 # 之前咱们学requests,可以发送htt ...

  2. Python爬虫-爬取京东商品信息-按给定关键词

    目的:按给定关键词爬取京东商品信息,并保存至mongodb. 字段:title.url.store.store_url.item_id.price.comments_count.comments 工具 ...

  3. 利用selenium爬取京东商品信息存放到mongodb

    利用selenium爬取京东商城的商品信息思路: 1.首先进入京东的搜索页面,分析搜索页面信息可以得到路由结构 2.根据页面信息可以看到京东在搜索页面使用了懒加载,所以为了解决这个问题,使用递归.等待 ...

  4. 八个commit让你学会爬取京东商品信息

    我发现现在不用标题党的套路还真不好吸引人,最近在做相关的事情,从而稍微总结出了一些文字.我一贯的想法吧,虽然才疏学浅,但是还是希望能帮助需要的人.博客园实在不适合这种章回体的文章.这里,我贴出正文的前 ...

  5. 正则爬取京东商品信息并打包成.exe可执行程序。

    本文爬取内容,输入要搜索的关键字可自动爬取京东网站上相关商品的店铺名称,商品名称,价格,爬取100页(共100页) 代码如下: import requests import re # 请求头 head ...

  6. 正则爬取京东商品信息并打包成.exe可执行程序

    本文爬取内容,输入要搜索的关键字可自动爬取京东网站上相关商品的店铺名称,商品名称,价格,爬取100页(共100页) 代码如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 ...

  7. python爬虫——用selenium爬取京东商品信息

    1.先附上效果图(我偷懒只爬了4页)  2.京东的网址https://www.jd.com/ 3.我这里是不加载图片,加快爬取速度,也可以用Headless无弹窗模式 options = webdri ...

  8. 爬虫之selenium爬取京东商品信息

    import json import time from selenium import webdriver """ 发送请求 1.1生成driver对象 2.1窗口最大 ...

  9. Java爬虫爬取京东商品信息

    以下内容转载于<https://www.cnblogs.com/zhuangbiing/p/9194994.html>,在此仅供学习借鉴只用. Maven地址 <dependency ...

随机推荐

  1. 【poj3764】The xor-longest Path

    The xor-longest Path Description In an edge-weighted tree, the xor-length of a path p is defined as ...

  2. GIT使用笔记一:GIT初始化配置

    本人系统环境:centos6.5 下 LNMP centos下git安装很简单sudo yum install gitOK 可先进行git 的全局配置 用户信息 git config --global ...

  3. (转)Linxu磁盘体系知识介绍及磁盘介绍

    Linxu磁盘体系知识介绍及磁盘介绍 系统管理 / 2017-01-14 / 0 条评论 / 浴春风 Linu磁盘设备基础知识指南磁盘速度快具备的条件: 1)主轴的转速5400/7200/10000/ ...

  4. 牛客网Java刷题知识点之什么是代码块、普通代码块、静态代码块、同步代码块、构造代码块以及执行顺序

    不多说,直接上干货! 这种形式的程序段我们将其称之为代码块,所谓代码块就是用大括号({})将多行代码封装在一起,形成一个独立的数据体,用于实现特定的算法.一般来说代码块是不能单独运行的,它必须要有运行 ...

  5. 如何优化Mysql执行查询数据的速度

    在项目中数据量小的情况下使用like查询速度还行,但是随着数据一天一天增加,再使用like进行模糊查询的时候速度上就会显得比较慢,现提供两套解决方案: 问题: 使用like查询效率很慢 select ...

  6. Spring RestTemplate实现服务间的远程调用完整代码示例

    父pom: 服务提供方 pom: provider配置文件: provider启动类: provider实体类: provider Mapper: 内置了增删改查的方法 provider Servic ...

  7. 关于window.event.returnValue=false的用处

    window.event.returnValue=false放在提交表单中的onclick事件中则不会提交表单,如果放到超链接中则不执行超链接,也就是它禁止了或取消了请求,没有任何效果. 比如: if ...

  8. dos 删除文件夹 rd

    windows普通方法删除不了文件.文件夹?那么试试dos命令吧. rd的另外一个写法是rmdir,源自ReMakeDirectory.使用的方法也很简单:rd 文件夹名 即可,例如:rd test. ...

  9. MySQL memory引擎 table is full 问题处理

    解决mysql的内存表“table is full”错误   101209 13:13:32 [ERROR] /usr/local/mysql/bin/mysqld: The table ‘test_ ...

  10. Python3+Selenium3+webdriver学习笔记13(js操作应用:弹出框无效如何处理)

    #!/usr/bin/env python# -*- coding:utf-8 -*-'''Selenium3+webdriver学习笔记13(js操作应用:弹出框无效如何处理)'''from sel ...