Python印象
Python现如今已成为IT行业的热门语言,每一个爱好学习的,或者说想发展的更好的个人和企业都需要去了解学习,现在是一个数据的时代,纷杂而数量庞大,一款优秀的数据处理语言必不可少,这也是现在Python大热的一个重要原因;Python的语言非常简洁,很少的代码量就可以写出高效的脚本。
我在生活中就很喜欢一些简约的东西,纯色的衣服、纯色单线条的笔,简单的人、简洁高效的语言、简洁整齐的代码。。。
所以,我喜欢Python
以后我会不定期发布自己的学习收获,分享学习所得。
最近武汉肺炎形式严峻,希望各位朋友注意安全,公共场所尽量不去或带上口罩(医用口罩即可)
注意个人卫生和饮食习惯,严防疾病传播,过个好年
辟谣:4G、5G不会传播肺炎
网页数据爬取
接下来我们看一个Python的小Demo,网页数据爬取处理(下面代码可直接复制使用测试)
- 先上代码(完整)
# 请求库
import requests
# 解析库
from bs4 import BeautifulSoup
# 用于解决爬取的数据格式化
import io
import sys
# 引入pymssql模块
import pymssql
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# 获取新闻列表页内容
headers = {
'user-agent': 'Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / '
'53.0.2785.104Safari / 537.36Core / 1.53.4882.400QQBrowser / 9.7.13059.400 '
}
r = requests.get('http://www.healthnet.com.cn/content_list.jspx?channelId=91', headers=headers)
# 类型
print(r.status_code)
# 中文显示
r.encoding = None
result = r.text
# 再次封装,获取具体标签内的内容
bs = BeautifulSoup(result, 'html.parser')
# 具体标签
print("解析后的数据")
num = 0
for tag in bs.find_all('div', class_='list-container cl'):
num = num + 1
print("计数:" + str(num))
# print(tag)
m_title = tag.find('h2').get_text()
m_summer = tag.find('p', class_='summary').get_text()
m_publicDate = tag.find('span', class_="smart-date").get_text()
m_href = tag.find('a').get('href')
# 获取每条新闻详情页内容
r1 = requests.get(m_href, headers=headers)
bs1 = BeautifulSoup(r1.text, 'html.parser')
sour = bs1.find('span', class_='resourse').a.get_text()
con = bs1.find(id="fbox").get_text()
# 插入数据库
connect = pymssql.connect('.', 'sa', '1', 'test') # 建立连接
if connect is None:
break
cursor = connect.cursor() # 创建一个游标对象,python里的sql语句都要通过cursor来执行
sql = "INSERT INTO [test].[dbo].[News]([NewsTitle],[NewsSummer],[NewsContents],[NewsHref],[NewsPublicDate]," \
"[NewsSource])VALUES('" + m_title + "','"+m_summer+"','"+con+"','"+m_href+"','"+m_publicDate+"','"+sour+"') "
cursor.execute(sql) # 执行sql语句
connect.commit() # 必须要提交
cursor.close()
connect.close()
2. 分块解析
(1) 引入库
# 请求库
import requests
# 解析库
from bs4 import BeautifulSoup
# 用于解决爬取的数据格式化
import io
import sys
# 引入pymssql模块
import pymssql
这一块是引入公共库,requests 数据请求库,BeautifulSoup 网页数据解析库 pymssql SQLServer 数据库处理库
注: BeautifulSoup库使用 pip install BeautifulSoup4 安装的是最新版(我的是4.8.2)的,版本大于4.0,不支持Python3.5以下版本,BeautifulSoup3 已经不提供维护和更新
(2)网页数据获取
注意不适配的 hearder可能导致获取不到数据,header可自行百度
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# 获取新闻列表页内容(中国健康网)
headers = {
'user-agent': 'Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / '
'53.0.2785.104Safari / 537.36Core / 1.53.4882.400QQBrowser / 9.7.13059.400 '
}
r = requests.get('http://www.healthnet.com.cn/content_list.jspx?channelId=91', headers=headers)
# 类型
print(r.status_code)
# 中文显示
r.encoding = None
result = r.text
(3)网页数据解析
BeautifulSoup作用:从Html或者Xml解析数据
使用方法请参考 https://blog.csdn.net/jia666666/article/details/82107815
# 再次封装,获取具体标签内的内容
bs = BeautifulSoup(result, 'html.parser')
# 具体标签
print("解析后的数据")
num = 0
for tag in bs.find_all('div', class_='list-container cl'):
num = num + 1
print("计数:" + str(num))
# print(tag)
m_title = tag.find('h2').get_text()
m_summer = tag.find('p', class_='summary').get_text()
m_publicDate = tag.find('span', class_="smart-date").get_text()
m_href = tag.find('a').get('href')
# 获取每条新闻详情页内容
r1 = requests.get(m_href, headers=headers)
bs1 = BeautifulSoup(r1.text, 'html.parser')
sour = bs1.find('span', class_='resourse').a.get_text()
con = bs1.find(id="fbox").get_text()
(4)存入数据库
# 插入数据库
connect = pymssql.connect('.', 'sa', '1', 'test') # 建立连接
if connect is None:
break
cursor = connect.cursor() # 创建一个游标对象,python里的sql语句都要通过cursor来执行
sql = "INSERT INTO [test].[dbo].[News]([NewsTitle],[NewsSummer],[NewsContents],[NewsHref],[NewsPublicDate]," \
"[NewsSource])VALUES('" + m_title + "','"+m_summer+"','"+con+"','"+m_href+"','"+m_publicDate+"','"+sour+"') "
cursor.execute(sql) # 执行sql语句
connect.commit() # 必须要提交
cursor.close()
connect.close()
(5)建表语句
USE [test]
GO
/****** Object: Table [dbo].[News] Script Date: 2020/1/22 10:10:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[News](
[ID] [int] IDENTITY(1,1) NOT NULL,
[NewsTitle] [nvarchar](200) NULL,
[NewsSummer] [nvarchar](300) NULL,
[NewsContents] [nvarchar](max) NULL,
[NewsHref] [nvarchar](200) NULL,
[NewsPublicDate] [nvarchar](50) NULL,
[NewsSource] [nvarchar](50) NULL,
[CreateTime] [datetime] NOT NULL,
[State] [char](10) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[News] ADD CONSTRAINT [DF_News_CreateTime] DEFAULT (getdate()) FOR [CreateTime]
GO
ALTER TABLE [dbo].[News] ADD CONSTRAINT [DF_News_State] DEFAULT ((1)) FOR [State]
GO
祝大家新年快乐,在病毒肆虐的日子可以过一个好年