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

【数据采集】获取网站数据(二)数据采集 系列包含 获取网站数据 一 获取网站数据 二 获取网站数据 二 1 常用的数据采集 python 库 Beautiful Soup https www crummy

大家好,我是讯享网,很高兴认识大家。

【数据采集】系列包含:

  • 获取网站数据(一)
  • 获取网站数据(二)

获取网站数据(二)

1.常用的数据采集python库

  • Beautiful Soup:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/
  • pyspider:http://docs.pyspider.org/en/latest/
  • Scrapy:https://scrapy-chs.readthedocs.io/zh_CN/0.24/#
  • selenium:https://selenium-python-zh.readthedocs.io/en/latest/

2.实例

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

导入需要的包。

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!") 

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

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

小讯
上一篇 2025-03-18 12:10
下一篇 2025-01-26 21:32

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/54744.html