十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
在Python中,获取数据的方式主要取决于数据的存储方式和来源,以下是一些常见的数据获取方法:

目前创新互联已为近1000家的企业提供了网站建设、域名、虚拟主机、网站改版维护、企业网站设计、抚州网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。
1、从文件中读取数据
1.1 从文本文件中读取数据
“`python
with open(‘file.txt’, ‘r’) as file:
data = file.read()
“`
1.2 从CSV文件中读取数据
“`python
import csv
with open(‘file.csv’, ‘r’) as file:
reader = csv.reader(file)
for row in reader:
print(row)
“`
1.3 从JSON文件中读取数据
“`python
import json
with open(‘file.json’, ‘r’) as file:
data = json.load(file)
“`
2、从网络获取数据
2.1 使用requests库获取网页数据
“`python
import requests
response = requests.get(‘https://www.example.com’)
data = response.text
“`
2.2 使用BeautifulSoup库解析网页数据
“`python
from bs4 import BeautifulSoup
import requests
response = requests.get(‘https://www.example.com’)
soup = BeautifulSoup(response.text, ‘html.parser’)
“`
3、从数据库获取数据
3.1 使用sqlite3库操作SQLite数据库
“`python
import sqlite3
conn = sqlite3.connect(‘database.db’)
cursor = conn.cursor()
cursor.execute(‘SELECT * FROM table_name’)
data = cursor.fetchall()
conn.close()
“`
3.2 使用pymysql库操作MySQL数据库
“`python
import pymysql
conn = pymysql.connect(host=’localhost’, user=’username’, password=’password’, database=’database_name’)
cursor = conn.cursor()
cursor.execute(‘SELECT * FROM table_name’)
data = cursor.fetchall()
conn.close()
“`
4、从API获取数据
4.1 使用requests库调用RESTful API
“`python
import requests
response = requests.get(‘https://api.example.com/data’)
data = response.json()
“`
以上就是Python中获取数据的常见方法。