python3 爬虫 全站_【Python3爬虫-爬图片】爬中国国家地理全站1.7万张图片

声明:爬虫为学习使用,请各位同学务必不要对当放网站或i服务器造成伤害。务必不要写死循环。

(注意保存地址写对,比如:root_file = "f:222" + "/"  # 分类的文件夹)

-

思路:古镇——古镇列表(循环获取古镇详情href)——xx古镇详情(获取所有img的src)

-

需要安装requests:

pip install requests# 低版本Python需要去除SSL验证:

import ssl

# 获取网页

ssl._create_default_https_context = ssl._create_unverified_context # 去除低版本Python验证SSL证书行为

response = urllib.request.urlopen(url)

html = response.read().decode('utf-8') # 编码格式gb2312,utf-8,GBK

html_string = str(html) # 转换成string,可以直接向数据库添加

-

1.  单分类爬:from bs4 import BeautifulSoup

import urllib.request

import requests

import os

import re

# 保存文章里面的图片

def down(url, num):

# 获取网页

response = urllib.request.urlopen(url)

html = response.read().decode('utf-8') # 编码格式gb2312,utf-8,GBK

html_string = str(html) # 转换成string,可以直接向数据库添加

soup = BeautifulSoup(html_string, "html.parser") # 解析网页标签

# 匹配抓取区域

# 该div的class由img和aImg两种,要判断一下

pid = soup.findAll('div', {"class": "img"})

if len(pid) == 0:

pid = soup.findAll('div', {"class": "aImg"})

pass

print(pid)

pid2 = soup.find("article").find("h1") # 本篇文章的标题

# 清除html标签

pattern = re.compile(r']+>', re.S)

txt = pattern.sub('', str(pid2))

print(txt)

for img_html in pid:

img_src = img_html.find('img')['src']

root = "D:/python/do/spider/guojiadili/" + txt + "/" # 没有最后一级文件夹目录则会自动创建

img_name = img_src.split("/")[-1].replace('@!rw9', '').replace('@!rw14', '').replace('@!rw7', '').replace('@!rw8', '').replace('@!rw10', '').replace('@!rw11', '').replace('@!rw12', '').replace('@!rw13', '').replace('@!rw6', '').replace('@!rw5', '').replace('@!rw4', '').replace('@!rw3', '').replace('@!rw2', '').replace('@!rw1', '').replace('@!rw15', '').replace('@!rw16', '').replace('@!rw17', '').replace('@!rw18', '').replace('@!rw19', '') # 去除图片后缀后面的特殊字符串,得到真实图片名

print(img_name)

path = root + img_name # 保存文件的名字

# 保存图片到本地

try:

if not os.path.exists(root):

os.mkdir(root)

if not os.path.exists(path):

r = requests.get(img_src)

r.raise_for_status()

# 使用with语句可以不用自己手动关闭已经打开的文件流

with open(path, "wb") as f: # 开始写文件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值