python在eclipse环境下的爬虫
用到的包:
import re
import urllib.request
运用正则需要这个jieba库哦
不足之处,希望各位帮忙指出
谢谢啦!
思路
首先明确目标:
-得到每一章的标题
-得到每一章的内容
网页链接(url):https://xs.sogou.com/list/6232872035/
分析网页源代码可知 该小说的章节url是由两串字符拼凑起来的,
1:先得到主url的html
2:在html通过正则截取到每一章的url,在一个列表里htmlList[]
(先拼凑再写入列表里)
3:接着定义一个函数,用来得到章节的html
4:然后通过正则截取内容
5:正则截取每一章的标题
6:将得到的正文写入文件(每章的标题名设为文件名 .txt)
注意:由于是多级爬取,每一章的url都不一样,那么要等前一个写入完成才能访问下一章的url.
7:可以通过循环将内容写入
for i in range(0,5): #只爬取前5章的内容
x=chapList[i] #每一章的标题
url2=htmlList[i] #每一章的url
print(url2)
html2=getMhtml(url2) #得到每一章的html
htmlList2=getzh(html2) #得到其中一章的正文
write_in_file('{}.txt'.format(x),htmlList2)
为什么只爬取前5章呢?
因为这本小说一共1000多张,全爬取电脑cpu可能会瘫,或者直接终止运行
(可以试试,我没试过)
我之前爬它们的链接的时候eclipse就终止运行了,我也只是在网页运行的代码,检测是否有错。
8:然后找到建的包,右键+刷新(refresh)就能看到了
到此这个小爬虫就结束了
当然后面自己也可以尝试去修改,或是去爬取其他小说,举一反三嘛
完整 代码
@requires_authorization
#coding:utf-8
'''
爬取网络小说《武道神尊》
author@初学者_言
'''
import urllib.request
import re
#获得第一主html
def getHtml(url1):
#打开链接
page=urllib.request.urlopen(url1)
html1=page.read()
html1=html1.decode('utf-8')
return html1
#得到每个章节的url列表
def getZlian(html):
reg=r'<a class="text-ellips" pbtag="\d+" href="(.+?)" target'
zhre=re.compile(reg)
htmlList=re.findall(zhre,html)
c='https://xs.sogou.com'
return ['https://xs.sogou.com{}'.format(i) for i in htmlList]
#得到每个章节的html
def getMhtml(url2):
page1=urllib.request.urlopen(url2)
html2=page1.read()
html2=html2.decode('utf-8')
#正则截取正文,定规则:左边起始位置,右边(末尾)结束位置
left = html2.find("contentWp")
right = html2.rfind("flwxBottom")
html2 = html2[left:right]
#截取到的正文有些特殊符号的字符串,需要用正常符号替代
dic = {"\r":'',"“":"“","”":"”","…":"..."}
for i in dic:
html2 = html2.replace(i,dic[i])
return html2
#得到正文内容,在一个列表里
def getzh(html2):
reg2=r'<p>(.+?)</p>'
zhre=re.compile(reg2)
htmlList2=re.findall(zhre,html2)
return htmlList2
#将内容写入文件
def write_in_file(filename,li):
with open(filename,'w') as f:
for m in li:
f.write(m +'\n')
#得到目录表,并将每一章的标题写入文件
def getChapter(html1):
rec=r'<a class="text-ellips" pbtag="\d+" href=".+?" target="_blank"><span>(.+?)</span>'
chare=re.compile(rec)
#html=html.decode('utf-8')
chapList = re.findall(chare,html1)
return chapList
html1=getHtml("https://xs.sogou.com/list/6232872035/")
htmlList=getZlian(html1)
chapList=getChapter(html1)
for i in range(0,5): #只爬取前5章的内容
x=chapList[i] #每一章的标题
url2=htmlList[i] #每一章的url
print(url2)
html2=getMhtml(url2) #得到每一章的html
htmlList2=getzh(html2) #得到其中一章的正文
write_in_file('{}.txt'.format(x),htmlList2)
print('ok') #用来检验程序是否进行完
**注意:**在此,首先对被爬取方说声抱歉(虽然是免费小说),尊重正版小说,此文仅是为了学术交流以及经验分享,别学坏哦。
小白:后面还会写个爬取分页网页的代码,请期待一下
以上是我2018年写的,然后现在搜狗连域名都换了,好像小说也不见了
不过思路可以学习下
下面我贴个简单的爬虫的代码吧(帮同学们交交作业,哈哈)
#coding:utf-8
'''
Created on 2019年12月5日
@author: xxxx
'''
import requests
import re
import pandas
from bs4 import BeautifulSoup
headers = {
'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3732.400 QQBrowser/10.5.3819.400',
'Host':'music.douban.com'
}
url = 'https://music.douban.com/chart'
res = requests.get(url,headers=headers,timeout = 10)
soup = BeautifulSoup(res.text,'html.parser')
musary=[]
i=1
while(i<=10):
info={}
#歌曲
mus_name = soup.select('.icon-play a')[i-1]
#歌手、播放次数
singer = soup.select('.intro p')[i-1]
sing = singer.text.split('/',1)
#print(sing)
te1=sing[0].strip('\xa0')
te2=sing[1].strip('\xa0')
ct=te2.strip("次播放")
#上榜次数
dayNum = soup.select('.days')[i-1].text
days =re.findall(r'\d+',dayNum)
info['歌曲']=mus_name.text
info['歌手']=te1
info['播放次数']=ct
info['上榜天数']=days[0]
musary.append(info)
i=i+1
while(i>10 and i<=20):
info={}
#歌曲
mus_name = soup.select('.icon-play a')[i-1]
#歌手、播放次数
singer = soup.select('.intro p')[i-1]
h1=singer.text.strip('\n')
h2=h1.split('/',1)
te=h2[0].split('\n',1)
te1=te[1].strip()
te2=h2[1].strip()
ct=te2.strip("次播放")
#上榜次数
dayNum = soup.select('.days')[i-1].text
days =re.findall(r'\d+',dayNum)
info['歌曲']=mus_name.text
info['歌手']=te1
info['播放次数']=ct
info['上榜天数']=days[0]
musary.append(info)
i=i+1
order = ['歌曲', '歌手', '播放次数', '上榜天数']
df = pandas.DataFrame(musary)
df = df[order]
df.to_excel('musary.xlsx')