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

【数据采集】系列包含:


获取网站数据(二)

1.常用的数据采集python库

2.实例

中传要闻 为例,获取相关的新闻信息(新闻标题、新闻链接、新闻来源、发布日期、浏览量、新闻内容、图片链接),并存入数据库中。

本文代码已放在我的GitHub上,需要的朋友可以自行获取。
https://github.com/Beracle/07-public-opinion-analysis/blob/main/cuc_news_all.ipynb

导入需要的包。

import requests
import re
import pymysql
from bs4 import BeautifulSoup as bs
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

函数 savenews() 用来将采集的数据存入数据库中。

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

函数 parsecontent() 用来解析某个特定网页,网址由 newsurl 参数传入。最后的返回值包括:新闻发布部门、新闻发布日期、浏览量、新闻中包含的所有图片链接、新闻内容。

def parsecontent(newsurl):
    try:
        option = webdriver.ChromeOptions()
        option.add_argument('headless') # 设置不打开浏览器
        # executable_path是谷歌浏览器的驱动路径,请确保已安装
        bro = webdriver.Chrome(options = option,executable_path=r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")
        bro.get(newsurl)
        html_source = bro.page_source
        soup = bs(html_source,"html.parser")
        
        #新闻标题
        h1 = soup.find_all("h1")
        
        info = soup.find_all("span",attrs={"class":"arti-name"})
        infotxt = info[0].get_text()       
        department = infotxt[infotxt.find('来源:')+3:infotxt.find('20')] #发表部门
        newsdate = infotxt[infotxt.find('20'):infotxt.find('20')+10] #发表日期
        r = re.compile('[\u4e00-\u9fa5]+')
        dep = r.findall(department)
        
        countinfo = soup.find_all("span",attrs={"class":"WP_VisitCount"})
        count = countinfo[0].get_text()
        
        all_image = soup.find("article",attrs={"class":"con-area"}).find_all('img')
        piclinks = ''
        for i in range(len(all_image)):
            if all_image[i] != '':
                link = 'http://www.cuc.edu.cn/_upload/'+str(all_image[i])[str(all_image[i]).find('src="')+14:str(all_image[i]).find('.')+4]
                piclinks = piclinks + link + ' '
        
        contentinfo = soup.find_all("div",attrs={"class":"wp_articlecontent"})
        content = contentinfo[0].get_text()
        
        bro.quit()
    except:
        print('data-error')
    
    return dep[0],newsdate,count,piclinks,content

为什么上面的代码要用到 selenium.webdriver(),按照下面这么写不就好了。

url = 'http://www.cuc.edu.cn/news/2021/0311/c1901a178638/page.htm'
r=requests.get(url)
code=r.encoding
content=r.content
rt=str(content,"utf-8")
soup=bs(rt,"html.parser")
print(soup)

在这里插入图片描述
观察实际输出,我们发现显示的浏览量和实际的浏览量并不一致。

这里简单解释一下。浏览器的右键 “查看源代码” 看到的是网页文件最原始的代码,没有经过 js 运算;F12 查看到的开发者工具中的 html 代码,是经过 js 运算过的代码。浏览器在接收完 html 后才执行 js 代码。因而如果是服务器端脚本,“查看源代码”是服务器端生成的 html,还没经过 js 运算。

看一下使用 selenium.webdriver 的运行结果。

url = 'http://www.cuc.edu.cn/news/2021/0311/c1901a178638/page.htm'
option = webdriver.ChromeOptions()
option.add_argument('headless')
bro = webdriver.Chrome(options = option,executable_path=r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")
bro.get(url)
html_source = bro.page_source
soup = bs(html_source,"html.parser")
print(soup)

在这里插入图片描述

测试一下 parsecontent() 函数。

parsecontent("http://www.cuc.edu.cn/news/2021/0311/c1901a178638/page.htm")

在这里插入图片描述

对于每一条新闻的 url 调用 parsecontent() 函数,再调用 savenew() 函数将每条新闻的相关信息存入数据库。

urlpath="http://www.cuc.edu.cn/news/1901/list"
try:
    for i in range(1,4):
        url=urlpath+str(i)+".htm"
        #print(url)
        r=requests.get(url)
        code=r.encoding
        content=r.content
        rt=str(content,"utf-8")
        soup=bs(rt,"html.parser")
        href=soup.find_all("h3",attrs={'class','tit'})
        for h in href:
            newsurl=h.find_all('a')
            urllen=str(newsurl[0]).find('target')
            newsurl=str(newsurl[0])[9:urllen-2]
            newsurl="http://www.cuc.edu.cn"+newsurl
            title=h.get_text()
            print(title) 
            print("------Save Start!---------")
            department,date,count,piclinks,content = parsecontent(newsurl)
            savenews(title,newsurl,department,date,count,content,piclinks)
            print("------Save Sucess!---------")
            #savenews(title,newsurl)
except:
    print("Error!")

在这里插入图片描述
在这里插入图片描述

可以看到,数据已被成功存入数据库。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

G皮T

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

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

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

打赏作者

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

抵扣说明:

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

余额充值