简单静态网页爬取数据存储

文章目录

  • 将数据存储为JSON文件
    • 存储数据
    • 读取数据
  • 将数据存储到MySQL数据库
    • 存储数据
    • 读取数据

将数据存储为JSON文件

存储数据

# 将获取的文本使用dump方法写入JSON文件

# 2020中国大学100强

import requests
from lxml import etree
import json


url = 'http://www.gaosan.com/gaokao/196075.html'
data = requests.get(url).content
s = etree.HTML(data)


name = s.xpath(
    '//*[@id="data196075"]/table[1]/tbody/tr/td[2]/text()')  # 大学名称


with open('ouput.json', 'w') as fp:

    json.dump(name, fp)

读取数据

f=open('ouput.json')
data=json.load(f)
print(data)

简单静态网页爬取数据存储_第1张图片

将数据存储到MySQL数据库

存储数据

import json
from lxml import etree
import requests
import pymysql

db = pymysql.connect(host="localhost", user="root",
                     password="root", database="daxuepaiming")
cursor = db.cursor()


url = 'http://www.gaosan.com/gaokao/196075.html'
data = requests.get(url).content
s = etree.HTML(data)


names = s.xpath(
    '//*[@id="data196075"]/table[1]/tbody/tr/td[2]/text()')  # 大学名称

for n in names:
    n = str(n)
    cursor.execute("insert into dxpm(name)values('%s');" % (n))
db.commit()
db.close()

读取数据

import pymysql

db = pymysql.connect(host="localhost", user="root",
                     password="root", database="daxuepaiming")
cursor = db.cursor()
data=cursor.execute('select * from dxpm')
data=cursor.fetchall()
for d in data:
    print(d)
db.close()

因查询数据太多,截取了部分数据展示
简单静态网页爬取数据存储_第2张图片

你可能感兴趣的:(Python网络爬虫技术,数据库,mysql,python,大数据,json)