【数据采集】获取网站数据(一)

【数据采集】系列包含:


获取网站数据(一)

抓取“中传要闻”中所有的新闻标题及其 URL,并存入数据库或文本文档中。

在这里插入图片描述

首先看一下网页结构。

import requests as re

url = 'http://www.cuc.edu.cn/news/1901/list.htm'
r = re.get(url)
code = r.encoding
rt = r.content
rhtml = str(rt,'utf-8') #避免中文乱码
print(code)

在这里插入图片描述

print(rhtml)

在这里插入图片描述
我们利用 BeautifulSoup 自动解析 HTML。

Beautiful Soup 是一个可以从 HTML 或 XML 文件中提取数据的 Python 库。它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式。Beautiful Soup 会帮你节省数小时甚至数天的工作时间。

https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

from bs4 import BeautifulSoup as bs
import pymysql

将获取的标题和链接存入数据库。

def save_news(title,url):
    #pysql.connect(数据库URL,用户名,密码,数据库名)
    db = pymysql.connect("localhost","root","密码","数据库名",charset="utf8")
    cursor = db.cursor()
    try:
        cursor.execute('INSERT INTO cucnews(title,url) VALUES(%s,%s)', (title,url))
        db.commit()
    except:
        print('数据库连接错误!')
        db.rollback()
    db.close()

循环获取每个页面所有的新闻标题和链接。

try:
    for i in range(1,3):
        url = 'http://www.cuc.edu.cn/news/1901/list' + str(i) + '.htm'
        r = re.get(url)
        r_content = r.content
        r_html = str(r_content,'utf-8')
        soup = bs(r_html,'html.parser')
        title = soup.find_all('h3',attrs={'class','tit'})
        for j in title:
            news_url = j.find_all('a')
            url_len = str(news_url[0]).find('target')
            tit = j.get_text()
            url = 'http://www.cuc.edu.cn'+(str(news_url[0])[9:url_len-2])
            save_news(tit,url)
except:
    print('error')

查看数据库。

在这里插入图片描述
可以看到数据已经被存入数据库啦。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

G皮T

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

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

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

打赏作者

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

抵扣说明:

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

余额充值