当前位置:   article > 正文

【数据采集】获取网站数据(二)_获取网站服务器数据

获取网站服务器数据

【数据采集】系列包含:


获取网站数据(二)

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

函数 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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

函数 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

为什么上面的代码要用到 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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

这里简单解释一下。浏览器的右键 “查看源代码” 看到的是网页文件最原始的代码,没有经过 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在这里插入图片描述

测试一下 parsecontent() 函数。

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

在这里插入图片描述

对于每一条新闻的 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!")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/691357
推荐阅读
相关标签
  

闽ICP备14008679号