您的位置:首页 > 编程语言 > Python开发

python爬虫-利用request,bs4(BeautifulSoup)获取天天书屋的在线阅读内容并存为txt文档

2018-08-04 15:18 691 查看

大致思路是从该书籍的阅读首页开始,利用request访问网页(利用了代理ip,用户代理伪装),然后将解码获得的文件bs4搜索得到每一章的链接,并且访问他。

这是首页

查看源代码,不难找到存放章节链接的标签a

处理手段是利用bs4找到所有的a标签并且循环遍历a标签的列表,知道找到章节一的标签才开始操作。

 操作如下:

通过字符串拼接得到章节所在url,并且访问。

例如第一章:

参看源代码:

发现h1标签记录章节名称,且唯一,则通过bs4找到这个h1,提取string作为章节名称放入txt文件。

再次研究发现,章节文本内容通过<script src=/content2/bookbody4/bookid_18422476/579341534508.hl></script>这样的js写入,这里采用bs4配合re(正则表达式)准确找到这个script标签,并根据src的值访问js文件url获得整个js代码,并替换不合适字符得到 content字符串,作为章节内容写入txt,随后得到这个txt完整文件。

代码如下(有详细备注):

[code]#coding:utf-8
from urllib import request
from bs4 import BeautifulSoup
import re
# 处理写入文字内容的js代码中的占位符号
def solve_text(content):
content = content.replace("document.write('", "")
content = content.replace("' ;", "")
content = content.replace(")", " ")
content = content.replace("</br>", "\n")
content = content.replace("<br /><br />", "\n")
content = content.replace("&nbsp;", " ")
return content

if __name__ == '__main__':
with open('圣墟.txt', 'a', encoding='utf-8') as f:
index_url = 'http://www.ttshu.com/html/content/18424482.html'
start_url = "http://www.ttshu.com"
# 使用代理服务器访问
proxy = {'http': '206.125.41.135:80'}
proxy_handler = request.ProxyHandler(proxy)
opener = request.build_opener(proxy_handler)
request.install_opener(opener)
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36'
}
# 用户代理伪装
req = request.Request(url=index_url, headers=head)
rsp = request.urlopen(req)
# 解码获得的结果
html = rsp.read().decode('gb2312', 'ignore')
# 创建bs对象
soup = BeautifulSoup(html, 'html.parser')
chapters = soup.find_all("a")
start_download_flag = False
number = 0
# 开始寻找是章节的链接
for item in chapters:
# 找到了,从章节的标签开始,访问每个章节的链接
if start_download_flag is True:

# 拼接章节链接并访问
download_url = start_url + item['href']
download_req = request.Request(url=download_url, headers=head)
download_rsp = request.urlopen(download_req)
download_html = download_rsp.read().decode('gb2312', 'ignore')
download_soup = BeautifulSoup(download_html, 'html.parser')
# 找到章节名称的标签,并获取文本内容(也就是处理掉标签符号)
name = download_soup.find('h1').string + "\n"
f.write(name)
content_url = start_url+download_soup.find('script', src=re.compile("content2"))['src']
content_req = request.Request(url=content_url, headers=head)
content_rsp = request.urlopen(content_url)
content_html = content_rsp.read().decode("gb2312", 'ignore')
content = solve_text(content_html)
f.write(content+"\n")
number += 1
print("下载了"+str(number)+"章")
# 找到章节的a标签
if item.text == u'向站长举报错误章节':
start_download_flag = True

 这里强调必须使用html.parser解析器,使用lxml会找不全链接标签。

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: