说明:
可能经常出现要爬取某个网站的数据,这时候需要利用爬虫技术来完成,这块主要使用Python来实现。
如何搭建Python环境我上节文章有详细描述:使用Python3.7实现爬虫技术,获取自己想要的网站数据_学无耻境的博客-CSDN博客_python爬虫技术抓取网站数据
(1)导入包
import requests
from bs4 import BeautifulSoup
import re
import pymysql
beautifulsoup是python的一个HTML解析库,可以用它来方便地从网页中提取数据。
(2)发送请求并打印状态码
url = 'https://docs.microsoft.com/zh-cn/sql/mdx/mdx-function-reference-mdx?view=sql-server-2017'
res = requests.get(url)
res.encoding='utf-8'
print(res.status_code)
encoding='utf-8' 里面处理中文乱码
(3)分析网页发现所要的数据在<tbody>标签中
通过beautifulsoup查找到所有的函数以及描述数据
(4)通过正则表达式取出需要的数据
#re匹配需要的数据
pertern = re.compile(r'<a.*?><span data-stu-id="d5ccf-.*?">(.*?)</span>.*?</a>.*?<td><span data-ttu-id="d5ccf-.*?">(.*?)</span>.*?</td>',
re.S)
生成正则模式
data = str(data)
item = re.findall(pertern, data)
对data进行强制类型转换(转为字符串)
匹配出数据
(5)存入数据库
def create():
db = pymysql.connect("localhost", "root", "root", "test")#连接数据库
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS FUN_TEST")
sql = """CREATE TABLE FUN_TEST (
ID INT PRIMARY KEY AUTO_INCREMENT,
NAME CHAR(20),
DESCRIBE1 CHAR(255))"""
cursor.execute(sql)
db.close()
def insert(value):
db = pymysql.connect("localhost", "root", "root", "test")
cursor = db.cursor()
sql = "INSERT INTO FUN_TEST(NAME,DESCRIBE1) VALUES (%s, %s)"
try:
cursor.execute(sql,value)
db.commit()
print('插入数据成功')
except:
db.rollback()
print("插入数据失败")
db.close()
create() #创建表
首先创建表,如果存在相同名字的表,则删除;再创建表。
插入数据。
(6)源码
#!/usr/bin/python3
import requests
from bs4 import BeautifulSoup
import re
import pymysql
def create():
db = pymysql.connect(host='localhost',user='root',password='root',database='test')#连接数据库
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS FUN_TEST")
sql = """CREATE TABLE FUN_TEST (
ID INT PRIMARY KEY AUTO_INCREMENT,
NAME CHAR(20),
DESCRIBE1 CHAR(255))"""
cursor.execute(sql)
db.close()
def insert(value):
db = pymysql.connect(host='localhost',user='root',password='root',database='test')
cursor = db.cursor()
sql = "INSERT INTO FUN_TEST(NAME,DESCRIBE1) VALUES (%s, %s)"
try:
cursor.execute(sql,value)
db.commit()
print('插入数据成功')
except:
db.rollback()
print("插入数据失败")
db.close()
create() #创建表
#re匹配需要的数据
pertern = re.compile(r'<a data-linktype="relative-path" href=".*?">(.*?)</a>.*?<td>(.*?)</td>',
re.S)
url = 'https://docs.microsoft.com/zh-cn/sql/mdx/mdx-function-reference-mdx?view=sql-server-2017'
res = requests.get(url)
res.encoding='utf-8'
print(res.status_code)
soup = BeautifulSoup(res.text, 'html.parser')
data = soup.find_all('tbody')
print(data)
data = str(data)
item = re.findall(pertern, data)
print(item)
for i in item:
print(i)
insert(i)
参考网站:
https://blog.csdn.net/Air_RA/article/details/85225712#commentsedit