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)
相关推荐
逍遥友 2020-10-26
JnX 2020-06-27
sunzhihaofuture 2020-07-19
sunzhihaofuture 2020-06-06
oXiaoChong 2020-06-05
ARCXIANG 2020-06-05
夜斗不是神 2020-11-17
染血白衣 2020-11-16
ARCXIANG 2020-11-02
ARCXIANG 2020-10-28
CycloneKid 2020-10-27
荒谬小孩 2020-10-26
snakeson 2020-10-09
meylovezn 2020-08-28
囧芝麻 2020-08-17
数据挖掘工人 2020-08-15
cxcxrs 2020-07-28
dashoumeixi 2020-07-20