php抓取网页数据插入数据库(5.PHP倒序输出所有日志方法(一)输出方法)
优采云 发布时间: 2021-09-28 23:11php抓取网页数据插入数据库(5.PHP倒序输出所有日志方法(一)输出方法)
所以,我们需要引入一个时间函数,然后写一个函数来获取当前时间
import time
#获取当前时间
def getCurrentTime(self):
return time.strftime('[%Y-%m-%d %H:%M:%S]',time.localtime(time.time()))
#获取当前时间
def getCurrentDate(self):
return time.strftime('%Y-%m-%d',time.localtime(time.time()))
以上是获取具体时间和日期的函数。输出时,我们可以在输出语句之前调用这个函数。
然后我们需要将缓冲区设置输出到日志中,并在程序的开头添加这两个语句。
f_handler=open('out.log', 'w')
sys.stdout=f_handler
这样,print语句的所有输出内容都会保存到out.log文件中。
2.页码保存
爬虫在爬行的过程中可能会出现各种错误,从而导致爬虫的中断。如果我们重新运行爬虫,会导致爬虫从头开始运行,这显然是不合理的。因此,我们需要保存当前抓取的页面,比如可以保存为文本。如果爬虫中断,再次运行爬虫,读取文本文件的内容,然后爬取。
可以稍微参考一下函数的实现:
#主函数
def main(self):
f_handler=open('out.log', 'w')
sys.stdout=f_handler
page = open('page.txt', 'r')
content = page.readline()
start_page = int(content.strip()) - 1
page.close()
print self.getCurrentTime(),"开始页码",start_page
print self.getCurrentTime(),"爬虫正在启动,开始爬取爱问知识人问题"
self.total_num = self.getTotalPageNum()
print self.getCurrentTime(),"获取到目录页面个数",self.total_num,"个"
if not start_page:
start_page = self.total_num
for x in range(1,start_page):
print self.getCurrentTime(),"正在抓取第",start_page-x+1,"个页面"
try:
self.getQuestions(start_page-x+1)
except urllib2.URLError, e:
if hasattr(e, "reason"):
print self.getCurrentTime(),"某总页面内抓取或提取失败,错误原因", e.reason
except Exception,e:
print self.getCurrentTime(),"某总页面内抓取或提取失败,错误原因:",e
if start_page-x+1 < start_page:
f=open('page.txt','w')
f.write(str(start_page-x+1))
print self.getCurrentTime(),"写入新页码",start_page-x+1
f.close()
这样,无论我们在爬虫中遇到什么错误,妈妈都不会再担心了。
3.页面处理
在页面处理的过程中,我们可能会遇到各种奇怪的HTML代码。和上一节一样,我们可以继续使用页面处理类。
<p>
import re
#处理页面标签类
class Tool:
#将超链接广告剔除
removeADLink = re.compile('