导入模块
import re
import os
import urllib.request
# urllib 库
# requests:http请求模块,用来模拟请求
# error: 异常处理模块,如果出现请求出错,可以捕捉异常
# parse:提供url处理方法,如拆分,解析,合并等
# robotparse:识别网站的robots.txt文件,判断哪些网站可以爬取
# 发送请求的两种方法
# urlopen:最基本的构造http请求的方法,可get请求或post请求
# Requests:声明一个request对象,该对象可以包含header信息,然后用urlopen打开
# 设置请求头
# headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.42 Safari/537.36'}
# request = urllib.request.Request('http://www.baidu.com',headers=headers)
# response = urllib.request.urlopen(request)
# print(response.read().decode('utf-8')) # 解码后的请求,通过.decode()进行解码
# print(response.status) # 打印响应状态码
# print(response.getheaders()) #打印请求头信息
# 访问的网址
url = 'https://gz.lianjia.com/zufang/'
# 设置请求头
headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.42 Safari/537.36'}
request = urllib.request.Request(url,headers=headers)
# 打开访问的网址
response = urllib.request.urlopen(request)
# 通过状态码判断是否正常连接
if response.status == 200:
html = response.read().decode('utf-8') # 解码后的请求,通过.decode()进行解码
# 编写正则表达式
reg = r'data-src="(.*?.jpg)"'
imgre = re.compile(reg)
imglist = re.findall(imgre,html)
# 判断文件夹是否存在,如果不存在则创建
if os.path.exists('D:\\Desktop\\爬虫_anaconda\\爬虫_链家照片'):
print('文件夹存在')
os.chdir('D:\\Desktop\\爬虫_anaconda\\爬虫_链家照片')
else:
os.makedirs('D:\\Desktop\\爬虫_anaconda\\爬虫_链家照片')
print('创建文件夹')
os.chdir('D:\\Desktop\\爬虫_anaconda\\爬虫_链家照片')
# 循环下载图片并编辑名字
x = 1
for img in imglist:
img = img.replace('250x182','780x1439')
urllib.request.urlretrieve(img, '%s.jpg'%x)
print('正在下载第{}个图片'.format(x))
x +=1