python 爬取菜鸟教程程序记录

#!/usr/bin/env python3
import re
import html as ht   
import urllib.request

def craw(url, page):
    html = urllib.request.urlopen(url).read().decode('utf-8')  # 因为存在编码问题,所以先把html解码
    expNamePat = '<p><strong>(.+?)</strong>(.+?)</p>'  # 抓取题目描述的正则匹配
    expName = re.compile(expNamePat).findall(html)       # 抓到题目描述
    contentPat = '<div class="hl-main">(.*?)</span></div>'  # 抓取源码的正则匹配
    midResult = re.compile(contentPat, re.S).findall(html)[0]  # 这个时候抓到的内容是杂乱的,中间还包含很多无用的html标签
    re_h=re.compile('</?\w+[^>]*>')     # 用来取出html标签
    content = re_h.sub('', midResult)   # 去除html标签
    
    content = ht.unescape(content)     # 把抓到的内容在进行html解码
    file = open('test.c','w')                 # 把抓到的内容保存
    file.write(content)
    file.close()

for i in range(1,  2):
    url = 'http://www.runoob.com/cprogramming/c-exercise-example{}.html'.format(i)
    #print(url)
    craw(url, i)

这次先写一部分,完整的版本之后会更新

#!/usr/bin/env python3
import re
import html as ht
import urllib.request

def craw(url, page):
    html = urllib.request.urlopen(url).read().decode('utf-8')
    expNamePat = '<p><strong>(.+?)</strong>(.+?)</p>'
    expName = re.compile(expNamePat).findall(html)
    try:
        contentPat = '<div class="hl-main">(.*?)</span></div>'
        midResult = re.compile(contentPat, re.S).findall(html)[0]
        re_h=re.compile('</?\w+[^>]*>')
        content = re_h.sub('', midResult)
        content = ht.unescape(content)
        print('正在爬取第' + str(page) + '个程序...')
        file = open( str(page) +'-c语言编程实例.c','w')
        content = "//" + expName[0][0] + expName[0][1] + '\n' + content
        file.write(content)
        file.close()
    except:
        try:
            contentPat = '<p>程序源代码:</p>\n<pre>(.*?)</pre>'
            content = re.compile(contentPat, re.S).findall(html)[0]
            content = ht.unescape(content)
            print('正在爬取第' + str(page) + '个程序...')
            file = open( str(page) +'-c语言编程实例.c','w')
            content = "//" + expName[0][0] + expName[0][1] + '\n' + content
            file.write(content)
            file.close()
        except:
            pass
for i in range(1, 101):
    url = 'http://www.runoob.com/cprogramming/c-exercise-example{}.html'.format(i)
    #print(url)
    craw(url, i)

在这个过程中有些页面的标签有变动,就用了 try ...except...嵌套,而有些程序里面还有自定义的头文件,所以有些程序没有抓下来(具体是第50个)

  • 程序还有不足的地方,比如抓下来的文本没有保持原来的格式,
    在抓取标题的时候有些内容没抓下来
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容