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

yipeiwu_com4年前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爬虫入门教程--正则表达式完全指南(五)

python爬虫入门教程--正则表达式完全指南(五)

前言 正则表达式处理文本有如疾风扫秋叶,绝大部分编程语言都内置支持正则表达式,它应用在诸如表单验证、文本提取、替换等场景。爬虫系统更是离不开正则表达式,用好正则表达式往往能收到事半功倍的...

python基于BeautifulSoup实现抓取网页指定内容的方法

本文实例讲述了python基于BeautifulSoup实现抓取网页指定内容的方法。分享给大家供大家参考。具体实现方法如下: # _*_ coding:utf-8 _*_ #xiao...

python爬虫 批量下载zabbix文档代码实例

这篇文章主要介绍了python爬虫 批量下载zabbix文档代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 # -*- c...

python实现爬虫统计学校BBS男女比例之多线程爬虫(二)

接着第一篇继续学习。 一、数据分类 正确数据:id、性别、活动时间三者都有 放在这个文件里file1 = 'ruisi\\correct%s-%s.txt' % (startNum, e...

Python 抓取动态网页内容方案详解

Python 抓取动态网页内容方案详解

用Python实现常规的静态网页抓取时,往往是用urllib2来获取整个HTML页面,然后从HTML文件中逐字查找对应的关键字。如下所示: 复制代码 代码如下: import urlli...