python3下BeautifulSoup练习一(爬取小说)
上次写博客还是两个月以前的事,今天闲来无事,决定把以前刚接触python爬虫时的一个想法付诸行动:就是从网站上爬取小说,这样可以省下好多流量(^_^)。
因为只是闲暇之余写的,还望各位看官海涵;不足之处,不用客气///^_^.......
好了,上菜了‘(*>﹏<*)′
from bs4 import BeautifulSoup
import urllib.request
import re
import os,time def getUrls(url):
urls = []
#url = 'http://www.qu.la/book/1258/'
req = urllib.request.Request(url)
page = urllib.request.urlopen(req) html = page.read() soup = BeautifulSoup(html,'html.parser') i = 0
for k in soup.find_all(href=re.compile('.html')):
#print('www.qu.la'+k['href'],k.get_text())
if i != 0:
urls.append('http://www.qu.la'+k['href'])
i = i+1
return urls def getContent(url):
#url = 'http://www.qu.la/book/1258/759251.html'
headers = ('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11')
opener = urllib.request.build_opener()
opener.addheaders = [headers]
html = opener.open(url).read() soup = BeautifulSoup(html,'html.parser')
content = soup.find('div',id='content')
title = soup.find('h1')
return title.get_text(),content.get_text() if __name__ == '__main__':
urls = getUrls('http://www.qu.la/book/1258/')
#print(urls)
fp = open("异界之魔武流氓.txt","w")
for url in urls:
print(url)
title,content = getContent(url)
fp.write(title+"\n")
fp.write(content.replace(' ','\n')+"\n")
time.sleep(2)
fp.close()
print("Done")
getUrls()函数是为了从小说的目录页获取各章节的链接(这一步也可以获取到章节的名称(⊙o⊙)),getContent()是根据提供的章节链接从网页中获取章节的名称和内容。
估计网站有防爬虫的设置,以上代码在测试过程中并不能获取到所有章节 。。。。。。^_^|||
添加“user_agents”后,模拟多个浏览器访问则可以解决上述问题,同时修改了存入txt文件中的内容,去除获取到的文章内容中的广告信息。修改后的代码如下
from bs4 import BeautifulSoup
import urllib.request
import re
import os,time,random def getUrls(url):
urls = []
#url = 'http://www.qu.la/book/1258/'
req = urllib.request.Request(url)
page = urllib.request.urlopen(req) html = page.read() soup = BeautifulSoup(html,'html.parser') i = 0
for k in soup.find_all(href=re.compile('.html')):
#print('www.qu.la'+k['href'],k.get_text())
if i != 0:
urls.append('http://www.qu.la'+k['href'])
i = i+1
return urls def getContent(url):
#url = 'http://www.qu.la/book/1258/759251.html'
user_agents = [
'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
'Opera/9.25 (Windows NT 5.1; U; en)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7",
"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 ",
]
agent = random.choice(user_agents)
opener = urllib.request.build_opener()
opener.addheaders = [("User-agent",agent),("Accept","*/*"),]
html = opener.open(url).read()
'''
req = urllib.request.Request(url)
page = urllib.request.urlopen(req)
html = page.read()
''' soup = BeautifulSoup(html,'html.parser')
content = soup.find('div',id='content')
title = soup.find('h1')
return title.get_text(),content.get_text() if __name__ == '__main__':
urls = getUrls('http://www.qu.la/book/1258/')
#print(urls)
fp = open("异界之魔武流氓.txt","w")
i = 0
for url in urls:
print(url)
title,content = getContent(url)
fp.write(title+"\n")
content = content.replace(' ','\n')
fp.write(content[0:-71]+"\n")
#time.sleep(2)
fp.close()
print("Done")
python3下BeautifulSoup练习一(爬取小说)的更多相关文章
- Python3爬取小说并保存到文件
问题 python课上,老师给同学们布置了一个问题,因为这节课上学的是正则表达式,所以要求利用python爬取小说网的任意小说并保存到文件. 我选的网站的URL是'https://www.biquka ...
- python爬虫——爬取小说 | 探索白子画和花千骨的爱恨情仇(转载)
转载出处:药少敏 ,感谢原作者清晰的讲解思路! 下述代码是我通过自己互联网搜索和拜读完此篇文章之后写出的具有同样效果的爬虫代码: from bs4 import BeautifulSoup imp ...
- Python3.x:Selenium+PhantomJS爬取带Ajax、Js的网页
Python3.x:Selenium+PhantomJS爬取带Ajax.Js的网页 前言 现在很多网站的都大量使用JavaScript,或者使用了Ajax技术.这样在网页加载完成后,url虽然不改变但 ...
- python之爬取小说
继上一篇爬取小说一念之间的第一章,这里将进一步展示如何爬取整篇小说 # -*- coding: utf- -*- import urllib.request import bs4 import re ...
- 用Python爬取小说《一念永恒》
我们首先选定从笔趣看网站爬取这本小说. 然后开始分析网页构造,这些与以前的分析过程大同小异,就不再多叙述了,只需要找到几个关键的标签和user-agent基本上就可以了. 那么下面,我们直接来看代码. ...
- Python实战项目网络爬虫 之 爬取小说吧小说正文
本次实战项目适合,有一定Python语法知识的小白学员.本人也是根据一些网上的资料,自己摸索编写的内容.有不明白的童鞋,欢迎提问. 目的:爬取百度小说吧中的原创小说<猎奇师>部分小说内容 ...
- Scrapy爬取小说简单逻辑
Scrapy爬取小说简单逻辑 一 准备工作 1)安装Python 2)安装PIP 3)安装scrapy 4)安装pywin32 5)安装VCForPython27.exe ........... 具体 ...
- Golang 简单爬虫实现,爬取小说
为什么要使用Go写爬虫呢? 对于我而言,这仅仅是练习Golang的一种方式. 所以,我没有使用爬虫框架,虽然其很高效. 为什么我要写这篇文章? 将我在写爬虫时找到资料做一个总结,希望对于想使用Gola ...
- 利用python的requests和BeautifulSoup库爬取小说网站内容
1. 什么是Requests? Requests是用Python语言编写的,基于urllib3来改写的,采用Apache2 Licensed 来源协议的HTTP库. 它比urllib更加方便,可以节约 ...
随机推荐
- [CTSC2008]祭祀(二分图匹配)
没有SPJ时显然是不需要输出方案的.不需要输出方案很好做,先把边扩展(因为会往下流),然后求最大独立集,最大独立集=n-最小点覆盖,因为其是最大独立集的补集.如何求最小点覆盖呢?毕竟我写过最大权闭合子 ...
- c指针(1)
#include<stdio.h> void swap(int *a,int *b); void dummy_swap(int *a,int *b); int main() { ,d=; ...
- BBS项目架构实现
一.注册功能 注册页面搭建 auto_id 数据校验 使用forms组件实现(forms) 创建一个文件夹随意,创建一个.py中 在.py文件中创建类继承form.Form 创建字段实现,实现对字段的 ...
- POJ 2796 Feel Good 【单调栈】
传送门:http://poj.org/problem?id=2796 题意:给你一串数字,需要你求出(某个子区间乘以这段区间中的最小值)所得到的最大值 例子: 6 3 1 6 4 5 2 当L=3,R ...
- java常用工具类(一)
一.String工具类 package com.mkyong.common; import java.util.ArrayList; import java.util.List; /** * * St ...
- Proe5.0导出PDF至配置文件的相关方法,VC++
定义文件bcsMessage.txt PLM PLM PLM # login login 测试 # Active messagebox menu Active messagebox menu 激活菜单 ...
- 1.linux系统调优
首先来说调优是一门黑色艺术,使用来满足人的感知,通过人的感觉来进行配置,达到让人感觉操作系统速度很块的感觉. 操作系统拥有四个瓶颈:cpu,内存,网络,磁盘.调优主要是对上述四个子系统进行配置优化,其 ...
- 吴裕雄--天生自然 PYTHON3开发学习:面向对象
class MyClass: """一个简单的类实例""" i = 12345 def f(self): return 'hello wor ...
- DFS---迷宫问题
#include<iostream> #include<string> #include<cstring> using namespace std;//dfs in ...
- Ubuntu更改源地址列表
1. 备份源列表 sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup 2.打开源列表 sudo gedit /etc/apt/sour ...