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 爬虫抓站的一些技巧总结

使用python 爬虫抓站的一些技巧总结

学用python也有3个多月了,用得最多的还是各类爬虫脚本:写过抓代理本机验证的脚本,写过在discuz论坛中自动登录自动发贴的脚本,写过自动收邮件的脚本,写过简单的验证码识别的脚本,本...

Python实现的爬取豆瓣电影信息功能案例

Python实现的爬取豆瓣电影信息功能案例

本文实例讲述了Python实现的爬取豆瓣电影信息功能。分享给大家供大家参考,具体如下: 本案例的任务为,爬取豆瓣电影top250的电影信息(包括序号、电影名称、导演和主演、评分以及经典台...

python3实现抓取网页资源的 N 种方法

这两天学习了python3实现抓取网页资源的方法,发现了很多种方法,所以,今天添加一点小笔记。 1、最简单 import urllib.request response = url...

使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例

熟悉Java的jsoup包的话,对于Python的BeautifulSoup库应该很容易上手。 复制代码 代码如下:#coding: utf-8import sysimport urll...

python 爬虫百度地图的信息界面的实现方法

python 爬虫百度地图的信息界面的实现方法

在爬虫百度地图的期间,就为它做了一个界面,运用的是PyQt5。 得到意想不到的结果: # -*- coding: utf-8 -*- # Form implementation...