pyhton 网络爬取软考题库保存text

#-*-coding:utf-8-*-
#参考文档
#https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#find-all
import requests
import re
from bs4 import BeautifulSoup
html = requests.get('https://m.cnitpm.com/exam/ExamST1_1031655.htm/')
soup = BeautifulSoup(html.text,'lxml')
ulTag=soup.find_all('ul','tit')
#计数器每次调用加1
def create_counter():
def increase(): #定义一个还有自然数算法的生成器,企图使用next来完成不断调用的递增
n = 0
while True:
n = n+1
yield n
it = increase() #一定要将生成器转给一个(生成器)对象,才可以完成,笔者第一次做,这里一直出问题,
def counter(): #再定义一内函数
return next(it) #调用生成器的值,每次调用均自增
return counter
counter_ = create_counter() #用变量来指向(闭包函数返回的函数)
#保存文件
def save(filename, contents):
#print(counter_())
fh = open(filename, 'a+', encoding='utf-8')
#print(str(counter_())+contents.strip()+'\n')
fh.write(str(counter_())+'、'+contents.strip()+'\n')
fh.close()


###################################网络爬取页面分析
for item in ulTag:
a_temp=item.find_all('a')
#print(a_temp)
for aitem in a_temp:
#print (aitem.get('href'))
html2 = requests.get(aitem.get('href'))
#解决乱码问题
html2.encoding = 'utf-8'
soup2 = BeautifulSoup(html2.text, 'lxml')
divTag = soup2.find_all('div', 'tm-box')
for divitem in divTag:
#print(divitem.get_text())
#保存到文档
save('G:/aa/qa.txt',divitem.get_text())
#print(divTag.replace('[<div class="tm-box">', ''))



posted @ 2019-02-12 11:19  夏微风  阅读(963)  评论(0编辑  收藏  举报