python爬虫入门篇:保姆级教程手把手教你实现网络爬虫

28 篇文章 2 订阅
16 篇文章 1 订阅

一、前言

上篇爬虫入门篇笔记设计了基本的项目结构和对应的代码功能。根据设计好的项目结构,我们选定个目标网站进行实践采集,完成爬虫的具体实现。

二、需求分析

  • 目标网址:郑州工业大学新闻网
  • 目标数据:
    • 新闻链接(url)
    • 新闻标题(tile)
    • 发布时间(datetime)
    • 浏览次数(visitcount)

三、代码实现

  • URL管理器
# 待爬取集合
new_urls = set()
# 已爬取集合
old_urls = set()


def add_new_url(url):
    '''
    添加新URL到待爬取集合中
    
    input:
        url
        
    output:
        无
    '''
    new_urls.add(url)


def add_new_urls(urls):
    '''
    一次性添加多个URLs到待爬取集合中
    
    input:
        urls
        
    output:
        无
    '''
    for url in urls:
        new_urls.add(url)


def get_new_url():
    '''
    从待爬取集合中获取一个新的待爬取URL
    
    input:
       无
       
    output:
       url
    '''

    next_url = new_urls.pop()
    return next_url


def has_new_url():
    '''
    判断是否还有待爬取URL
    
    input:
       无
    
    output:
       True or False
    '''
    result = False
    if new_urls:
        result = True
    return result
  • 网页下载器
from urllib import request

def download(url):
    '''
    下载参数url指示的网页数据,并将网页数据全部返回

    input:
        url
        
    output:
        网页数据
    '''
    response = request.urlopen(url)
    html_cont = response.read().decode("utf-8")
    return html_cont
  • 数据处理器
data_list = []

def collect_data(data):
    data_list.append(data)

def output_html():
    fout = open('output.html', 'w', encoding='utf-8')

    fout.write('<html>')
    fout.write('<head><meta charset="utf-8"></head>')
    fout.write('<body>')
    fout.write('<table>')

    for dataitem in data_list:
        try:
            fout.write('<tr>')
            fout.write('<td>%s</td>' % dataitem['url'])
            fout.write('<td>%s</td>' % dataitem['title'])
            fout.write('<td>%s</td>' % dataitem['datetime'])
            fout.write('<td>%s</td>' % dataitem['visitcount'])
            fout.write('</tr>')
        except BaseException as e:
            print("新闻《" + dataitem['title'] + "》写入失败")
            print(e)

    fout.write('</table>')
    fout.write('</body>')
    fout.write('</html>')

    fout.close()
  • 爬虫解析器和爬虫启动器代码见资源文件。代码较长就不放上来了。
    四、测试结果

爬虫的基本代码思路千篇一律,只要掌握了里面的逻辑,我们可以对爬虫进行更多拓展,进阶更高级的爬虫。

  • 39
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code_space

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值