爬虫学习(十二)——bs4实践案例
实践项目————诗词名句网《三国演义》小说爬取
import os
import re
import time
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup def header():
# 三国演义网址
article_url = "http://www.shicimingju.com/book/sanguoyanyi.html"
# 模拟浏览器创建请求头
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36"}
# 创建请求对象
request = urllib.request.Request(article_url,headers=headers)
return request # 发送请求
def main(request):
# 创建管理器对象对象
handler = urllib.request.HTTPHandler()
# 使用管理器对象构建请求对象
opener = urllib.request.build_opener( handler )
# 使用opener进行获取响应
response = opener.open( request )
return response # 下载内容
def download():
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36"}
request = header()
response = main(request).read()
# 使用bs4对html进行解析
article_main_html = BeautifulSoup(response,"lxml")
if not os.path.exists("三国演义"):
os.mkdir("三国演义")
# 获取书名
# article_name =article_main_html.select(".book-header h1").text
# 获取书名详解
# article_details =article_main_html.select(".book-summary p").text
# 获取章节链接
article_section = article_main_html.select(".book-mulu ul li a")
section_title_ls = []
section_url_ls = []
# 将章节和章节链接有序存入列表中
for section in article_section:
section_title_ls.append(section.text)
section_url_ls.append(section["href"]) # 分章节爬取章节内容
for num in range(0,120):
# 同时取出章节名和章节url进行请求数据
section_title = section_title_ls[num]
section_url = section_url_ls[num]
# 拼接完整的章节url
section_allurl = "http://www.shicimingju.com"+section_url
section_request = urllib.request.Request(section_allurl,headers=headers )
handler = urllib.request.HTTPHandler
opener =urllib.request.build_opener(handler)
# 请求章节数据
section_response = opener.open(section_request).read().decode("utf8")
# 使用bs4对html进行解析
article_soup =BeautifulSoup(section_response,"lxml")
article_content = article_soup.select(".chapter_content")
# 构建章节名并和文章组合
content = section_title+article_content[0].text
# 创建存储文件名
filename ="三国演义"+".doc"
print("正在下载第%d章"%num)
# 将下载的数据写入文件中
filename_path = os.path.join("三国演义",filename)
with open(filename_path,"ab+") as tf:
tf.write(content.encode("utf8"))
tf.close()
# 防止暴力请求
time.sleep(2) if __name__ == '__main__':
download()
百度音乐爬取案例
import os
import re
import time
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
import json # 面向对象爬取数据
class BaiDuMusic( object ): # 初始化输入参数
def __init__(self, singer, page):
self.singer = singer
self.page = page
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36"} # 构建请求头信息
def header(self):
url = "http://music.taihe.com/search/song?"
data = {
"s": "1",
"key": self.singer,
"jump": "0",
"start": (self.page - 1) * 20,
"size": "20",
"third_type": "0",
}
# 解析参数
data = urllib.parse.urlencode( data )
singer_url = url + data
# 创建请求头
request = urllib.request.Request( url=singer_url, headers=self.headers )
return request # 创建管理器对象,请求数据
def requset(self):
request = self.header()
handler = urllib.request.HTTPHandler()
opener = urllib.request.build_opener( handler )
response = opener.open( request )
return response # bs4解析数据
def paserSong(self):
response = self.requset()
singer_soup = BeautifulSoup( response, "lxml" )
pattern=re.compile(r'[\d]+')
# bs4匹配目标标签<li>
songs_info =singer_soup.find_all(name="li", attrs={"data-albumid":pattern})
# 获取<li>标签中的”data-songitem“属性,并将属性值转成json格式
song_ls =[json.loads(li["data-songitem"]) for li in songs_info]
song_info=[(song_info["songItem"]["sname"],song_info["songItem"]["sid"]) for song_info in song_ls]
# print(song_info)
# 输出结果如下,获取歌曲id
# """[('只要平凡', 598740690), ('My Sunshine', 127018924), ('听', 123192697), ('微笑着胜利(庆祝建军91周年网宣主题曲)', 601622060), ('Lost In The Stars', 268791350), ('Everything Will Say Goodbye', 285312563), ('《星辰》——电视剧《择天记》片头曲', 609686640), ('听', 123206622), ('Give You My World', 277779153), ('微笑着胜利(庆祝建军91周年网宣主题曲)(伴奏)', 601622061), ('My Sunshine', 131096021), ('三生三世', 537883379), ('着魔', 53603708), ('三生三世', 537883380), ('Torches', 541943830), ('浩瀚', 124796979), ('逆战', 14944589), ('剑心', 121223583), ('天下', 1103789), ('燕归巢', 136982116)]"""
return song_info
def downloadSong(self):
if not os.path.exists('music'):
os.mkdir('music')
song_info =self.paserSong()
for song_detail in song_info:
song_info_id=song_detail[1]
song_info_name=song_detail[0]
print("正在下载第%s页的:%s的《%s》"%(self.page,self.singer,song_info_name))
# 通过该API接口获取歌曲信息的json格式数据
song_url ='http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play&format=jsonp&callback=jQuery17202741599001012014_1513517333931&songid=%s&_=1513517334915'%song_info_id
# 获取请求
request_song_detail =urllib.request.urlopen(song_url)
# 解析json歌曲数据
pattern_song =re.compile(r'\((.*)\)',re.S)
json_song_info=pattern_song.findall(request_song_detail.read().decode("utf8"))
# 将字符串数据转化成json数据,便于提取下载路径
lrclink=json.loads(json_song_info[0])["songinfo"]["lrclink"]
file_link =json.loads(json_song_info[0])["bitrate"]["file_link"]
# 创建文件格式保存文件
filename_music=song_info_name+"_%s.mp3"%self.singer
filename_lrc =song_info_name+"_%s.lrc"%self.singer
song_path = os.path.join("music",filename_music)
lrc_path = os.path.join("music",filename_lrc)
try:
# 下载歌曲和歌词数据
urllib.request.urlretrieve(lrclink,lrc_path)
urllib.request.urlretrieve( file_link, song_path )
time.sleep(1)
print("《%s》下载完成"%song_info_name)
except Exception as e:
print("因版权受限无法下载") # 录入爬取信息
def main():
singer = input( "请输入爬取的歌手或是歌名:" )
start_page = int( input( "请输入爬取的开始页:" ) )
end_page = int( input( "请输入爬取的终止页:" ) )
for page in range( start_page, end_page + 1 ):
baidumusic = BaiDuMusic( singer, page )
if page>end_page+1:
print("%s歌手的所有歌曲都已下载完毕"%singer)
baidumusic.downloadSong() # 运行
if __name__ == '__main__':
main()
爬虫学习(十二)——bs4实践案例的更多相关文章
- Python爬虫学习:二、爬虫的初步尝试
我使用的编辑器是IDLE,版本为Python2.7.11,Windows平台. 本文是博主原创随笔,转载时请注明出处Maple2cat|Python爬虫学习:二.爬虫的初步尝试 1.尝试抓取指定网页 ...
- scrapy爬虫学习系列二:scrapy简单爬虫样例学习
系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备: http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...
- (转)SpringMVC学习(十二)——SpringMVC中的拦截器
http://blog.csdn.net/yerenyuan_pku/article/details/72567761 SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter, ...
- 爬虫系列(十二) selenium的基本使用
一.selenium 简介 随着网络技术的发展,目前大部分网站都采用动态加载技术,常见的有 JavaScript 动态渲染和 Ajax 动态加载 对于爬取这些网站,一般有两种思路: 分析 Ajax 请 ...
- 爬虫学习(二)--爬取360应用市场app信息
欢迎加入python学习交流群 667279387 爬虫学习 爬虫学习(一)-爬取电影天堂下载链接 爬虫学习(二)–爬取360应用市场app信息 代码环境:windows10, python 3.5 ...
- 软件设计师【软件工程:软件开发模型、XP极限编程十二最佳实践】
一.软件开发模型 二.XP极限编程十二最佳实践
- Scala学习十二——高阶函数
一.本章要点 在Scala中函数是”头等公民“(可以作为参数,返回值,赋值给其他); 可以创建匿名函数,通常还会交给其他函数; 函数参数可以给出需要稍后执行的行为; 许多集合方法都接受函数参数,将函数 ...
- 【Hadoop学习之十二】MapReduce案例分析四-TF-IDF
环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 jdk8 hadoop-3.1.1 概念TF-IDF(term fre ...
- JVM学习十二:JVM之性能监控工具
前面我们学习了很多JVM相关的理论知识,那么本节将重点讲述的是工具的使用,正所谓:工欲善其事,必先利其器.因此,本节介绍常用的性能监控工具,用于性能监控和问题排查. 一.系统性能监控 系统性能工具用于 ...
随机推荐
- Docker学习笔记(1)-简介
1. 简介 Docker使用Google公司推出的Go语言开发实现,基于Linux内核的cgroup, namespace以及AUFS类的UnionFS等技术,对进程进行封装隔离,属于操作系统层面的虚 ...
- LCS与打印路径
/* LCS */ #include<bits/stdc++.h> using namespace std; const int maxn = 1000; int dp[maxn][max ...
- H-ui出现提交后没办法关闭
可以用sublime代替服务器来解决,或者是webstorm可以自行搭建服务器来解决当前的问题. sublime可以更改端口号 自己加上一个服务器 默认打开浏览器的 “快捷键”
- vue学习中遇到的onchange、push、splice、forEach方法使用
最近在做vue的练习,发现有些js中的基础知识掌握的不牢,记录一下: 1.onchange事件:是在域的内容改变时发生,单选框与复选框改变后触发的事件. 2.push方法:向数组的末尾添加一个或多个元 ...
- MVC在页面View上获取当前控制器名称、Action名称以及路由参数
有时候在封装MVC通用控件时需要在页面上获取这些数据. 用以下方法即可: //获取控制器名称: ViewContext.RouteData.Values["controller"] ...
- python--Time(时间)模块
要使用一个模块,首先要把模块导入进来 import time 我们先把这一篇文章需要用的模块导入进来 首先说一下time模块,time模块中的函数 --sleep:休眠指定的秒数(可以是小数) imp ...
- react- 相关
生命周期方法 组件的生命周期分成三个状态: Mounting:已插入真实 DOM Updating:正在被重新渲染 Unmounting:已移出真实 DOM React 为每个状态都提供了两种处理函数 ...
- 20170802,css样式优先级
样式的优先级 多重样式(Multiple Styles):如果外部样式.内部样式和内联样式同时应用于同一个元素,就是使多重样式的情况. 一般情况下,优先级如下: (外部样式)External styl ...
- 处理移动端自适应布局的方法- calc()与vw
在处理移动端自适应布局时,目前前端最流行的方法应该就是使用媒体查询,来设置HTML的字体大小,然后用rem为单位对Dom的宽高进行设置,这个方法的优势在于兼容性方面很好,劣势则在于当前市场上不同的机型 ...
- (六)JavaScript之[Regular Expression]与[错误(try, catch, throw)]
10].正则表达式 /** * 正则表达式(Regular Expression): * * 用于文本搜索和文本替换 * */ /** * /good/i是一个正则表达式. * good是一个模式(用 ...