爬虫:爬取新闻内容及图片,存入数据库

目录

一、需求

二、代码


一、需求

1、对新闻主页上的新闻进行爬取,要求解析出标题、内容、新闻类型、图片并存入数据库。

2、只爬取带有图片的新闻,一张即可。

二、代码

以下是对新华网爬取的代码示例。

import requests as rq
from bs4 import BeautifulSoup
import re,os
import datetime
from datetime import timedelta
from difflib import SequenceMatcher
from gbase import GBASE_DB 
from conf import IMGPATH,LOCALPATH,PICSIZE

xinhua_dict = {'politics':1, #时政
               'culture':2, #文化
               'health':3,  #健康
               'fortune':4,  #财经
               'world':5,  #国际
               }
    
def classify_news(s, news_list):
    for li in news_list:
        if li in s:
            return li
    return None
    
def get_xinhua_news(url):
    '''
    爬取新华网标题、内容、分类、图片
    '''
    newsWeb = rq.get(url)
    newsWeb.encoding = 'utf-8'
    soup = BeautifulSoup(newsWeb.text,'html.parser')
    #获取标题
    title_element = soup.find('span', class_='title')
    title = title_element.get_text(strip=True)
    #获取分类
    news_type = xinhua_dict[classify_news(url,xinhua_dict.keys())]
    #获取内容
    content_element = soup.find('div', id='detail')
    paragraphs = content_element.find_all('p')
    content = '\n'.join(paragraph.get_text(strip=True) for paragraph in paragraphs)
    content = re.sub('\n+', '\n', content).replace('"', '\\"').replace('\n', '\\n')
    #获取图片
    jpg_element = soup.find_all('img')
    jpg_pattern = re.compile(r'src="([^"]*1n\.(jpg|jpeg))"')
    j_list = jpg_pattern.findall(str(jpg_element))
    for j in j_list:
        jpg_path = os.path.basename(j[0])
        jpg_url = url[:url.find('c_')] + jpg_path
        picture = rq.get(jpg_url)
        if picture.status_code==200:
            if len(picture.content)>PICSIZE:
                with open(LOCALPATH+jpg_path,"wb") as f:
                    f.write(picture.content)
                return_path = IMGPATH+jpg_path
                break
        else:
            pass
    return title,news_type,content,return_path

def main():
    db = GBASE_DB()
    newsUrl = 'http://www.xinhuanet.com/'
    newsWeb = rq.get(newsUrl)
    newsWeb.encoding = 'utf-8'
    soup = BeautifulSoup(newsWeb.text,'lxml')
    #获取新闻网址列表
    link_list = []
    li_elements = soup.find_all('li')
    for li_element in li_elements:
        a_element = li_element.find('a')
        if a_element:
            url = a_element.get('href')
            if url.startswith("http://www.news.cn/") and url.endswith(".htm") and 'c_' in url and classify_news(url,xinhua_dict.keys())!=None:
                link_list.append(url)

    #逐个解析新闻网址
    for link in link_list:
        try:
            title,news_type,content,jpg_path = get_xinhua_news(link)

            sql = '''insert into table_name(title,type,content,image) 
                     values ('{}', {},'{}','{}')
                  '''.format(title,news_type,content,jpg_path)
            db.execute_sql(sql)
            print('(成功)爬取新华网:',title)
        except Exception as e:
            print('爬取失败:',link,' :',e)
            continue
            
if __name__ == '__main__':
    main()

首先,对新华网主页进行爬取,获取页面上所有的新闻链接,存放进入link_list列表中。

然后,依次访问每一个新闻链接,并解析标题、内容,需要对空格、特殊字符等做一下清洗。根据子频道路径进行分类,并爬取像素值大于阈值的图片(避免爬取到页面上的二维码等小图),图片保存在服务器本地某个文件夹下,如果没有符合条件的图片,则会报错,在main函数中抛出异常,跳过此新闻链接的爬取。

最后,存入数据库。

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据引用\[1\]和引用\[2\]的信息,我们可以使用爬虫将网页上的天气信息爬取下来,并存入SQLite数据库。首先,我们需要定位到需要爬取的数据所在的网页,即"http://www.tianqihoubao.com/lishi/beijing/month/202209.html"。然后,我们可以使用合适的爬虫工具,如Python的BeautifulSoup库,来解析网页内容并提取有用的数据。 在这个网页,天气信息按条分布,我们可以使用标签为'div',属性为'score'的元素来定位到每条天气信息。在每条天气信息,黑色圆圈表示学校的名称,我们可以将其作为'name-cn'字段存入数据库。另外,我们还需要提取总分字段,并将排名、姓名和总分存入包含排名、姓名、总分三列的表。 为了限制只爬取排名前15的学校,我们可以在爬取数据的过程设置一个计数器,当计数器达到15时停止爬取。 最后,我们可以使用数据可视化工具,如Matplotlib库,将学校名和总分进行柱形图可视化输出。 综上所述,我们可以通过爬虫将网页上的天气信息爬取下来,并存入SQLite数据库,然后使用柱形图对学校名和总分进行可视化输出。 #### 引用[.reference_title] - *1* *3* [实战:爬取数据存入数据库并做可视化分析](https://blog.csdn.net/npm_run_dev__/article/details/126979168)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [python爬虫爬取大学排名并存入数据库进行数据可视化](https://blog.csdn.net/weixin_46308934/article/details/122254991)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值