Python爬虫实现爬取京东手机页面的图片(实例代码)

yipeiwu_com5年前Python爬虫

实例如下所示:

__author__ = 'Fred Zhao'
 
import requests
from bs4 import BeautifulSoup
import os
from urllib.request import urlretrieve
 
class Picture():
 
 def __init__(self):
  self.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36'}
  self.base_url = 'https://list.jd.com/list.html?cat=9987,653,655&page='
  self.base_path = os.path.dirname(__file__)
 
 def makedir(self, name):
  path = os.path.join(self.base_path, name)
  isExist = os.path.exists(path)
  if not isExist:
   os.makedirs(path)
   print("File has been created.")
  else:
   print('OK!The file is existed. You do not need create a new one.')
  os.chdir(path)
 
 def request(self, url):
  r = requests.get(url, headers=self.headers)
  return r
 
 def get_img(self, page):
  r = self.request(self.base_url + str(page))
  plist = BeautifulSoup(r.text, 'lxml').find('div', id='plist')
  item = plist.find_all('li', class_='gl-item')
  print(len(item))
  self.makedir('pictures')
  num = 0
  for i in item:
   num += 1
   imglist = i.find('div', class_='p-img')
   print(num)
   img = imglist.find('img')
   print('This is %s picture' %num)
   if img.get('src'):
    url = 'https:' + img.get('src')
    fileName = img.get('src').split('/')[-1]
    urlretrieve(url, filename=fileName)
 
   elif img.get('data-lazy-img'):
    url = 'https:' + img.get('data-lazy-img')
    fileName = img.get('data-lazy-img').split('/')[-1]
    urlretrieve(url, filename=fileName)
 
 
 
if __name__ == '__main__':
 picture = Picture()
 for i in range(2): #控制爬取的页数
  picture.get_img(i+1)

以上这篇Python爬虫实现爬取京东手机页面的图片(实例代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

利用Python爬取可用的代理IP

利用Python爬取可用的代理IP

前言 就以最近发现的一个免费代理IP网站为例:http://www.xicidaili.com/nn/。在使用的时候发现很多IP都用不了。 所以用Python写了个脚本,该脚本可以把能用...

python抓取网页图片示例(python爬虫)

复制代码 代码如下:#-*- encoding: utf-8 -*-'''Created on 2014-4-24 @author: Leon Wong''' import urllib...

Python 3实战爬虫之爬取京东图书的图片详解

Python 3实战爬虫之爬取京东图书的图片详解

前言 最近工作中遇到一个需求,需要将京东上图书的图片下载下来,假如我们想把京东商城图书类的图片类商品图片全部下载到本地,通过手工复制粘贴将是一项非常庞大的工程,此时,可以用Python网...

python爬虫获取淘宝天猫商品详细参数

首先我是从淘宝进去,爬取了按销量排序的所有(100页)女装的列表信息按综合、销量分别爬取淘宝女装列表信息,然后导出前100商品的 link,爬取其详细信息。这些商品有淘宝的,也有天猫的,...

Python实现爬取百度贴吧帖子所有楼层图片的爬虫示例

Python实现爬取百度贴吧帖子所有楼层图片的爬虫示例

本文实例讲述了Python实现爬取百度贴吧帖子所有楼层图片的爬虫。分享给大家供大家参考,具体如下: 下载百度贴吧帖子图片,好好看 python2.7版本: #coding=utf-...