前言

发现很多人需要新闻的接口,所以自己去搜索了下,发现知乎上正好有对应的用户每天发布新闻简讯,所以自己想写一个新闻的爬虫。如果想做成接口的话,可以加上flask模块即可,这里就暂时只进行爬虫部分的编写。

目标站点

网址:https://www.zhihu.com/people/mt36501
通过这个网址进去,我只想要今天的内容,所以还要进行过滤。

开始编写代码

# 导入要使用的库
import requests, re, time
# 目标网址
url = 'https://www.zhihu.com/people/mt36501'
# 模拟请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362',
    'Accept': 'image/png, image/svg+xml, image/*; q=0.8, */*; q=0.5',
}
# 请求网址返回内容
resp = requests.get(url,headers=headers).text
# 过滤标题
h2 = re.findall(r'<h2 class="ContentItem-title">.*?</h2>', resp, re.S)
# 遍历每一个标题,因为发现有时候会发与新闻不想关的内容
for i in h2:
    # 获取当前日期
    now_time = time.strftime("%#m月%#d日", time.localtime())
    # 过滤出链接
    link = re.findall(r'href="(.*?)"', str(i), re.S)[0]
    # 过滤出标题
    title = re.findall(r'Title">(.*?)</a>', str(i), re.S)
    # 如果为空跳过
    if title == []:
        continue
    else:
        # 获取文章的日期
        title = str(title[0]).split(',')[0]
        # 文章日期与当前日期比较
        if title == now_time and link != '':
            #print(title, link)
            # 如果日期为今天,请求对应的网址,获取对应文章的内容
            con_resp = requests.get('https:' + link, headers=headers).text
            # 只要我们想要的内容,并过滤掉一些字符
            p = re.findall(r'<p>(.*?)</p>', con_resp.replace('"', '"').replace('&amp;', '&'), re.S)
            sum = 0
            text = ''
            # 遍历每一条获取到的新闻赋值给text
            for index, i in enumerate(p):
                sum += 1
                if sum == 1 | sum == 3:
                    continue
                    print(i)
                elif i == '':
                    print(i)
                    continue
                else:
                    if index == len(p) - 1:
                        text += i
                    else:
                        text += i + '\n\n'
print(text)

版权声明:本文为greensunit原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/greensunit/p/14630111.html