声明:爬虫为学习使用,请各位同学务必不要对当放网站或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: # 开始写文件