import urllib.request
import re
class neiHan:
#初始化页面
def __init__(self):
self.page=1;
#设置爬取开关
self.switch=True;
#下载模块
def loadPage(self):
# 获得网址,网页页面设置
url="https://yuedu.mipang.com/hchj/neihan/page-"+str(self.page)+".html"
#浏览器表头
headers= {"User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrom"
"e/17.0.963.56 Safari/535.11"}
#连接网址和浏览器表头
request=urllib.request.Request(url,headers=headers)
#获得网址数据
res=urllib.request.urlopen(request)
#读取网站数据
res1=res.read()
#数据转码
html=res1.decode()
#设置爬取规则
pattern=re.compile(‘<div\sclass="daoyu">(.*?)</div>‘,re.S)
#根据爬取规则获得数据
contentList=pattern.findall(html)
#遍历数据
for content in contentList:
print(content)
#将数据写入硬盘中
f=open("c://neiHan1.txt","a")
f.write(content)
f.close()
#循环模块
def starWork(self):
#确定爬取页数
while self.switch:
word=input("如果继续爬取数据,请按回车键(停止输入stop)")
if word=="stop":
self.switch=False
#没有输入停止,继续调用loadPage,爬取页面
self.loadPage()
self.page+=1
if __name__=="__main__":
#将类实例化
neiHanSpider=neiHan()
#调用循环模块
neiHanSpider.starWork()
原文:https://www.cnblogs.com/w331842/p/14644229.html