程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

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

发布于2019-08-07 16:40     阅读(830)     评论(0)     点赞(0)     收藏(0)


#-*-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">', ''))





所属网站分类: 技术文章 > 博客

作者:23hdsdh

链接:https://www.pythonheidong.com/blog/article/11598/ec5e4e2cb5631c287b20/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

0 0
收藏该文
已收藏

评论内容:(最多支持255个字符)