爬虫(网易新闻)

爬虫(网易新闻)

import os
import re
import requests

if not os.path.exists('网易新闻'):
    os.mkdir('网易新闻')

count = 0
for i in ['nba','cba','china']:
    # 获取所有的url
    response = requests.get(f'https://sports.163.com/{i}/')
    data = response.text
    url_res = re.findall('href="(https://sports.163.com/.*?)"', data)
    url_res = set(url_res)

    # 针对单个url

    for url in url_res:
        url_response = requests.get(url)
        url_data = url_response.text

        try:
            title = re.findall('<h1>(.*?)</h1>', url_data, re.S)[0]
            news_res = \
                re.findall('<div class="post_text" id="endText" style="border-top:1px solid #ddd;">(.*?责任编辑:.*?)</span>',
                           url_data, re.S)[0]  #
            news_res = re.sub('<.*?>', '', news_res)
        except:
            continue

        title = re.sub('[!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~,…]|\s', '', title)  # 除掉标题所有的脏字符
        title_path = os.path.join('网易新闻', f'{title}.txt')  # 拼接出新闻的路径
        f = open(title_path, 'w', encoding='utf8')

        f.write(news_res)
        f.flush()
        f.close()
        count += 1

        print(f'完成{count}篇, {title} done...')

转载于:https://www.cnblogs.com/yushan1/p/11232379.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值