使用request下载小说

使用requests

.title { text-align: center }
.todo { font-family: monospace; color: red }
.done { color: green }
.tag { background-color: #eee; font-family: monospace; padding: 2px; font-size: 80%; font-weight: normal }
.timestamp { color: #bebebe }
.timestamp-kwd { color: #5f9ea0 }
.right { margin-left: auto; margin-right: 0px; text-align: right }
.left { margin-left: 0px; margin-right: auto; text-align: left }
.center { margin-left: auto; margin-right: auto; text-align: center }
.underline { text-decoration: underline }
#postamble p,#preamble p { font-size: 90%; margin: .2em }
p.verse { margin-left: 3% }
pre { border: 1px solid #ccc; padding: 8pt; font-family: monospace; overflow: auto; margin: 1.2em }
pre.src { position: relative; overflow: visible; padding-top: 1.2em }
pre.src::before { display: none; position: absolute; background-color: white; top: -10px; right: 10px; padding: 3px; border: 1px solid black }
pre.src:hover::before { display: inline }
pre.src-sh::before { content: "sh" }
pre.src-bash::before { content: "sh" }
pre.src-emacs-lisp::before { content: "Emacs Lisp" }
pre.src-R::before { content: "R" }
pre.src-perl::before { content: "Perl" }
pre.src-java::before { content: "Java" }
pre.src-sql::before { content: "SQL" }
table { border-collapse: collapse }
caption.t-above { caption-side: top }
caption.t-bottom { caption-side: bottom }
td,th { vertical-align: top }
th.right { text-align: center }
th.left { text-align: center }
th.center { text-align: center }
td.right { text-align: right }
td.left { text-align: left }
td.center { text-align: center }
dt { font-weight: bold }
.footpara:nth-child(0n+2) { display: inline }
.footpara { display: block }
.footdef { margin-bottom: 1em }
.figure { padding: 1em }
.figure p { text-align: center }
.inlinetask { padding: 10px; border: 2px solid gray; margin: 10px; background: #ffffcc }
#org-div-home-and-up { text-align: right; font-size: 70%; white-space: nowrap }
textarea { }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00 }
.org-info-js_info-navigation { border-style: none }
#org-info-js_console-label { font-size: 10px; font-weight: bold; white-space: nowrap }
.org-info-js_search-highlight { background-color: #ffff00; color: #000000; font-weight: bold }

使用requests

Table of Contents

  • 1. 使用rquests

    • 1.1. 官方快速指导文档(最新版本,使用特定版本时注意版本号)
    • 1.2. 打开一个网址
    • 1.3. 发送其他请求
      • 1.3.1. 发送post请求请使用requests.post(url)
      • 1.3.2. 类似的,需要发送何种请求应该使用该种方法
      • 1.3.3. 包含cookies 在浏览器中得到cookies,传递给get(url,cookies=cookies)
    • 1.4. 判断是否正确打开并判断文件编码
      • 1.4.1. requests.codes.ok 成功
    • 1.5. 获得返回的内容
      • 1.5.1. 获取文本
      • 1.5.2. 获取二进制值
      • 1.5.3. 响应json
      • 1.5.4. 原始响应内容
    • 1.6. 写到文件
    • 1.7. 解析内容 BeautifulSoup
    • 1.8. 使用select寻找指定的对象
      • 1.8.1. 使用select获取指定标签,寻找的语法类似于css的选择器
      • 1.8.2. 获取标签名称和内容
  • 2. 实例
    • 2.1. 传递一些键值对来使用百度搜索
    • 2.2. 传递cookies登录微博
    • 2.3. 下载小说<道医天下>

1 使用rquests

1.1 官方快速指导文档(最新版本,使用特定版本时注意版本号)

http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#id2

1.2 打开一个网址

res = requests.get(url)

1.3 发送其他请求

1.3.1 发送post请求请使用requests.post(url)

1.3.2 类似的,需要发送何种请求应该使用该种方法

如: requests.put() requests.delete() requests.put() requests.options()

1.3.3 包含cookies 在浏览器中得到cookies,传递给get(url,cookies=cookies)

在chrome中获取cookies 在需要获取的页面上点开右上角竖着排列的三个点 更多工具–>开发者工具 NetWork中的name中的Headers中带有cookies

例如:微博登录的cookies就在namefavicon.ico中

1.4 判断是否正确打开并判断文件编码

res.encoding     #获取网页的编码  当给该属性赋值后,再次调用res.text,使用的是新的编码
res.status_code  #获取返回的http状态码

1.4.1 requests.codes.ok 成功

res.rails_for_status()   #当返回的值不是200时,会抛出异常

使用try except 将其包裹可以获得更明确的错误提示

try:
    res.rails_for_status()
except Exception as exp:
    print(exp)

1.5 获得返回的内容

1.5.1 获取文本

res.text type(res.text) #=> <class ‘str‘> 可以得知返回的值为str类型,那么,切片,in等就可以很方便的使用了

1.5.2 获取二进制值

也可以使用res.text 但是官方给出了使用content的示例

>>> from PIL import Image
>>> from io import BytesIO

>>> i = Image.open(BytesIO(r.content))

1.5.3 响应json

r.json() 当解析失败时会抛出异常

1.5.4 原始响应内容

r = requests.get(‘url‘, stream=True) 设置stream=True就可以获取原始套接字内容

1.6 写到文件

可以直接使用with open 的方式写入到文件,但是当文件过大时会占用大量内存, 所以一部分一部分写入

for part_file in res.iter_content(size):
    file.write(part_file)

设置size大小(kb),每次写入指定的大小

1.7 解析内容 BeautifulSoup

官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html 想要获得某些确定的内容,可以使用BeautifulSoup 下载包 pip3 install bs4 使用 import bs4

be = bs4.BeautifulSoup(htmlfile ,"html.parser")

1.8 使用select寻找指定的对象

1.8.1 使用select获取指定标签,寻找的语法类似于css的选择器

select(‘div‘) 返回所有div标签里的内容 ‘#id‘ id为id的 ‘.class‘ 所有类为类de ‘div .class‘ 所有div中包裹class的 ‘a[href]‘ 所有<a href=‘????‘>的 <a>可以还有其他属性 ‘a[href=‘https://www.baidu.com‘]‘ 所有<a href=‘https://www.baidu.com‘>的,<a>可以有其他属性 ‘div > a‘ <div><a> 中间不能有其他标签

1.8.2 获取标签名称和内容

select返回一个Tag对象的列表
eles = select(‘.menu‘)
type(eles)
# => class ‘list‘
# 输出全部匹配部分
print(eles)
# 输出某个匹配
print(eles[ 0])
# 输出标签中的值
# 例如: <a> 百度 </a> 会输出 百度
print(eles[ 0].getText()) # 会输出子标签的内容
print(eles[ 0].attrs)     # 不输出子标签的内容,只打印当前标签

2 实例

2.1 传递一些键值对来使用百度搜索

以百度为例 想要使用百度搜索,需要这样构建url https://www.baidu.com/s?wd=%E5%85%B3%E9%94%AE%E5%AD%97 那么我们想要得到这样的结果需要使用get(‘url‘, params=parameterdict) 例如:

search = input("请输入想要百度的内容")
baidu = ‘https://www.baidu.com/s?‘
search_params = {‘wd‘:search}
try:
    baidu_re = requests.get(baidu, params = search_params)
except Exception as err:
    print(err)
finally:
    pass

# 指定文件的写入编码,防止网页编码不是utf-8,并兼容win
with open(‘baidusearch.html‘, ‘w‘, encoding=baidu_re.encoding )as html:
    html.write(baidu_re.text)

2.2 传递cookies登录微博

因为微博的很多功能需要登录后才能使用,所以在获取信息时需要带着登录的cookies来操作 打开微博,登录,拿到cookies

import requests
cookies = {‘Cookie‘:‘值‘}  # 需要注意的是要把Cookie:SINAGLOBAL....全部复制出来
requests.get(‘微博的其他页面‘,cookies = cookies)
# 开始解析需要的内容即可

2.3 下载小说<道医天下>

"""
获取<道医天下>全部章节
"""
import requests,bs4,chardet
from io import StringIO
i = 1
strio = StringIO()
next_href = ‘http://www.ppxs.net/63/63820/19862177.html‘
text = ""
# 获取标题与正文,存放至StringIO流
def getUrlText(url):
    global i, next_href, page
    print("从该网页({})开始读取章节".format(url))
    page = requests.get(url)
    # 将字符编码设置为网页的编码,否则会有乱码
    page_text = page.text.encode(page.encoding)
    be = bs4.BeautifulSoup(page_text, "html.parser")
    i += 1
    next_page = be.select(".bottem a")
    next_href = next_page[3].attrs[‘href‘]
    print("下一章%s"%next_href)
    title = be.select(".bookname h1")
    title_text = title[0].text
    txt = be.select("#booktext")
    per_txt = txt[0].text
    # 每章开头都有,删掉
    in_text = per_txt.lstrip(‘‘‘<div class="content" id="booktext"><!--go-->
	    <p><font color="#FF0000" face="微软雅黑" size="3">人人小说欢迎您的光临,请记住本站地址:http://www.ppxs.net,手机阅读m.ppxs.net,以便随时阅读小说《道医天下》最新章节... </font></p>‘‘‘).replace("<br>","")
    inner_text = title_text+"\n"+in_text
    strio.write(inner_text)

#getUrlText(‘http://www.ppxs.net/63/63820/19862177.html‘)
try:
    while next_href != True:
	getUrlText(next_href)
	#next_href = getUrl(next_href)
	print(i)
except Exception as e:
    print(e)
finally:
    with open("道医天下.txt",‘a+‘) as a:
	a.write(strio.getvalue())

Author: vz liū

Created: 2017-04-04 Tue 13:28

Emacs 25.1.1 (Org mode 8.2.10)

时间: 2024-08-01 16:19:33

使用request下载小说的相关文章

下载小说并转成语音

最近迷上听小说了,但几个app上有声小说更新太慢,自己看小说的话不能同时去做其他事情,所以想了个办法从网上下载小说并将文字转换成语音.以后其他小说只需要改改下载小说地址即可.故写在博客上供以后使用. 一.main.py from spider import Spider from txt import Txt from mp3 import Mp3 if __name__ == '__main__': clsSpider = Spider() clsTxt = Txt() clsMp3 = Mp

Python脚本自动下载小说

本人喜欢在网上看小说,一直使用的是小说下载阅读器,可以自动从网上下载想看的小说到本地,比较方便.最近在学习Python的爬虫,受此启发,突然就想到写一个爬取小说内容的脚本玩玩.于是,通过在逐浪上面分析源代码,找出结构特点之后,写了一个可以爬取逐浪上小说内容的脚本. 具体实现功能如下:输入小说目录页的url之后,脚本会自动分析目录页,提取小说的章节名和章节链接地址.然后再从章节链接地址逐个提取章节内容.现阶段只是将小说从第一章开始,每次提取一章内容,回车之后提取下一章内容.其他网站的结果可能有不同

python爬虫之小说网站--下载小说(正则表达式)

思路: 1.找到要下载的小说首页,打开网页源代码进行分析(例:https://www.kanunu8.com/files/old/2011/2447.html) 2.分析自己要得到的内容,首先分析url,发现只有后面的是变化的,先获得小说的没有相对路径,然后组合成新的url(每章小说的url) 3.获得每章小说的内容,进行美化处理 代码如下: #小说爬虫 import requests import re url='https://www.kanunu8.com/book4/10509/' #因

第一个小爬虫(改进版)——下书网下载小说v2

已知问题: 代理地址需要更新 中断只能重新开始 1 import requests 2 import urllib.request 3 import re 4 import os 5 import string 6 import time 7 import random 8 from urllib import request 9 10 path = os.getcwd() # 获取当前路径 11 12 13 def open_url(url): 14 proxy_list = [ 15 {'h

第一个小爬虫——下书网下载小说v1

第一个小爬虫,问题较多! import urllib.request import re import os import string import time import random path = os.getcwd() # 获取当前路径 def get_url(): def open_url(url): req = urllib.request.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0;

以前写的一个下载小说的工具

因为当时发现只有一个站点有.但是时时联网的要求太让人不爽.就写了一个给全下下来了. 用到了: 1. 正则表达式,分析章节和内容: 2. 线程池下载,并且对下载中的相关超时做了一些处理: 3. 文件生成与写入,注意格式问题: 结合下载来说一下使用中的感受: 1. 下载并没有想像的飞一般的速度: 2. 经常会出现错误,章节读取不到,(估计是服务器无法响应): 3. 终于不用一直联网了. *__*

request下载进度显示,多线程爬取麦子学院视频

#encoding:utf8import _threadimport timeimport requestsfrom lxml import etreeimport reimport sysfrom contextlib import closing# 为线程定义一个函数class ProgressBar(object): def __init__(self, title, count=0.0, run_status=None, fin_status=None, total=100.0, uni

【爬虫】使用urllib.request去爬取小说

import urllib.request import re #1获取主页源代码 #2获取章节超链接 #3获取章节内容 #4下载小说 #驼峰命名法 #注释 获取小说内容 def getNovelContent(): #获取源代码 HTTP Response对象 html = urllib.request.urlopen('http://www.quanshuwang.com/book/0/269/') html = html.read() #print(html) #设置编码 html = h

免app下载笔趣阁小说

这个是对最近学习的一次总结吧.前两天写的,今天才有时间写博客. 偶然点开笔趣阁的网址(https://www.biquge.cc/),突然觉得我应该可以用爬虫实现小说下载.有这个想法我就开始尝试了. 爬虫呀,说白了就是程序自动模拟浏览器操作来获取网页的内容. 先用F12查看元素,查看章节网址链接,和章节正文内容. 结构很简单. 想法很快就有了,通过网站的搜索打开小说详情页,然后获取每一章的网址url,依次访问每一章网址,再通过正则表达式匹配章节内容, 最后将匹配的内容保存到本地. 中间忘了一个小