python抓取网页数据( Python的安装到开发工具的简单介绍--Python安装下载 )

优采云 发布时间: 2022-03-06 23:20

  python抓取网页数据(

Python的安装到开发工具的简单介绍--Python安装下载

)

  

  基于大众对 Python 的炒作和欣赏,作为一名 Java 从业者,在阅读了 Python 书籍之后,我决定成为一名 Python 爱好者。

  作为一个合格的脑残粉(题主ノ◕ω◕)ノ),为了我的线下开发,我会详细介绍Python安装到开发工具的简单介绍,写一个捕获天气信息数据并保存到数据库例子。(这个文章适合完全不懂Python的小白快速上手)

  如果你有时间,强烈建议跟上,因为介绍真的很详细。

  源码视频书练习题等资料可私信小编01获取

  1、Python 安装

  2、PyCharm(ide) 安装

  3、获取天气信息

  4、数据写入excel

  5、数据写入数据库

  1、Python 安装

  下载Python:官网地址:选择下载然后选择你的电脑系统,编辑器是Windows系统,所以选择

  

  

  

  2、Pycharm 安装

  下载PyCharm:官网地址:

  

  免费版可能会缺少一些功能,所以不推荐,所以这里我们选择下载企业版。

  安装 PyCharm 后,*** 打开可能需要您输入您的电子邮件地址或输入激活码

  获取免费激活码:

  3、获取天气信息

  我们计划采集的数据:杭州的天气信息,你可以先看看这个网站的杭州天气。

  实现数据抓取的逻辑:使用python请求URL,会返回对应的HTML信息。我们解析 HTML 以获取我们需要的数据。(很简单的逻辑)

  第 1 步:创建 Python 文件

  

  编写第一段 Python 代码

  if __name__ == '__main__':  url = 'http://www.weather.com.cn/weather/101210101.shtml'   print('my frist python file') 

  此代码类似于 Java 中的 Main 方法。您可以直接右键单击并选择运行。

  

  第 2 步:请求 RUL

  python的强大之处在于它拥有大量可以直接使用的模块(类似于Java jar包)。

  我们需要安装一个请求模块:File - Setting - Product - Product Interpreter

  

  

  单击如上所示的 + 号以安装 Python 模块。搜索

  

  顺便说一下,让我们安装一个 beautifulSoup4 和 pymysql 模块。beautifulSoup4 模块用于解析 HTML,可以将 HTML 字符串对象化。pymysql 模块用于连接 mysql 数据库。

  

  

  安装好相关模块后,就可以愉快的敲代码了。

  定义一个 getContent 方法:

  # 导入相关联的包 import requests import time import random import socket import http.client import pymysql from bs4 import BeautifulSoup def getContent(url , data = None):  header={  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',  'Accept-Encoding': 'gzip, deflate, sdch',  'Accept-Language': 'zh-CN,zh;q=0.8',  'Connection': 'keep-alive',  'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'  } # request 的请求头  timeout = random.choice(range(80, 180))  while True:  try:  rep = requests.get(url,headers = header,timeout = timeout) #请求url地址,获得返回 response 信息  rep.encoding = 'utf-8'  break  except socket.timeout as e: # 以下都是异常处理  print( '3:', e)  time.sleep(random.choice(range(8,15)))  except socket.error as e:  print( '4:', e)  time.sleep(random.choice(range(20, 60)))  except http.client.BadStatusLine as e:  print( '5:', e)  time.sleep(random.choice(range(30, 80)))  except http.client.IncompleteRead as e:  print( '6:', e)  time.sleep(random.choice(range(5, 15)))  print('request success')  return rep.text # 返回的 Html 全文 

  在主方法调用中:

  if __name__ == '__main__':  url ='http://www.weather.com.cn/weather/101210101.shtml'  html = getContent(url) # 调用获取网页信息  print('my frist python file') 

  第三步:分析页面数据

  定义一个 getData 方法:

  def getData(html_text):  final = []  bs = BeautifulSoup(html_text, "html.parser") # 创建BeautifulSoup对象  body = bs.body #获取body  data = body.find('div',{'id': '7d'})  ul = data.find('ul')  li = ul.find_all('li')  for day in li:  temp = []  date = day.find('h1').string  temp.append(date) #添加日期  inf = day.find_all('p')  weather = inf[0].string #天气  temp.append(weather)  temperature_highest = inf[1].find('span').string #***温度  temperature_low = inf[1].find('i').string # ***温度  temp.append(temperature_low)      temp.append(temperature_highest)  final.append(temp)  print('getDate success')  return final 

  上面的解析其实是按照HTML的规则来解析的。你可以在开发者模式下打开杭州天气(F12),看看页面的元素分布。

  

  在主方法调用中:

  if __name__ == '__main__':  url ='http://www.weather.com.cn/weather/101210101.shtml'  html = getContent(url) # 获取网页信息  result = getData(html) # 解析网页信息,拿到需要的数据  print('my frist python file') 

  将数据写入excel

  现在我们在 Python 中已经有了想要的数据,我们可以先将数据存储起来,比如将数据写入 csv。

  定义一个 writeDate 方法:

  import csv #导入包 def writeData(data, name):  with open(name, 'a', errors='ignore', newline='') as f:  f_csv = csv.writer(f)  f_csv.writerows(data)  print('write_csv success') 

  在主方法调用中:

  if __name__ == '__main__':  url ='http://www.weather.com.cn/weather/101210101.shtml'  html = getContent(url) # 获取网页信息  result = getData(html) # 解析网页信息,拿到需要的数据  writeData(result, 'D:/py_work/venv/Include/weather.csv') #数据写入到 csv文档中  print('my frist python file') 

  执行后在指定路径下会多出一个weather.csv文件,可以打开查看。

  

  

  这里最简单的数据采集——存储完成。

  将数据写入数据库

  因为数据一般存储在数据库中,所以我们以mysql数据库为例,尝试将数据写入我们的数据库。

  创建 WEATHER 表的第一步:

  创建表可以直接在mysql客户端进行,也可以在python中创建表。这里我们使用 python 创建一个 WEATHER 表。

  定义一个createTable方法:(import pymysql之前已经导入过,如果没有需要导入包)

  def createTable():  # 打开数据库连接  db = pymysql.connect("localhost", "zww", "960128", "test")  # 使用 cursor() 方法创建一个游标对象 cursor  cursor = db.cursor()  # 使用 execute() 方法执行 SQL 查询  cursor.execute("SELECT VERSION()")  # 使用 fetchone() 方法获取单条数据.  data = cursor.fetchone()  print("Database version : %s " % data) # 显示数据库版本(可忽略,作为个栗子)  # 使用 execute() 方法执行 SQL,如果表存在则删除  cursor.execute("DROP TABLE IF EXISTS WEATHER")  # 使用预处理语句创建表  sql = """CREATE TABLE WEATHER (  w_id int(8) not null primary key auto_increment,   w_date varchar(20) NOT NULL ,  w_detail varchar(30),  w_temperature_low varchar(10),  w_temperature_high varchar(10)) DEFAULT CHARSET=utf8""" # 这里需要注意设置编码格式,不然中文数据无法插入  cursor.execute(sql)  # 关闭数据库连接  db.close()   print('create table success') 

  在主方法调用中:

  if __name__ == '__main__':  url ='http://www.weather.com.cn/weather/101210101.shtml'  html = getContent(url) # 获取网页信息  result = getData(html) # 解析网页信息,拿到需要的数据  writeData(result, 'D:/py_work/venv/Include/weather.csv') #数据写入到 csv文档中  createTable() #表创建一次就好了,注意  print('my frist python file') 

  执行后,查看数据库,查看天气表是否创建成功。

  

  第二步,批量写入WEATHER表数据:

  定义一个 insertData 方法:

  def insert_data(datas):  # 打开数据库连接  db = pymysql.connect("localhost", "zww", "960128", "test")  # 使用 cursor() 方法创建一个游标对象 cursor  cursor = db.cursor()  try:  # 批量插入数据  cursor.executemany('insert into WEATHER(w_id, w_date, w_detail, w_temperature_low, w_temperature_high) value(null, %s,%s,%s,%s)', datas)  # sql = "INSERT INTO WEATHER(w_id,   # w_date, w_detail, w_temperature)   # VALUES (null, '%s','%s','%s')" %   # (data[0], data[1], data[2])  # cursor.execute(sql) #单条数据写入  # 提交到数据库执行  db.commit()  except Exception as e:  print('插入时发生异常' + e)  # 如果发生错误则回滚  db.rollback()  # 关闭数据库连接  db.close() 

  在主方法调用中:

  if __name__ == '__main__':  url ='http://www.weather.com.cn/weather/101210101.shtml'  html = getContent(url) # 获取网页信息  result = getData(html) # 解析网页信息,拿到需要的数据  writeData(result, 'D:/py_work/venv/Include/weather.csv') #数据写入到 csv文档中  # createTable() #表创建一次就好了,注意  insertData(result) #批量写入数据  print('my frist python file') 

  检查:执行完这条Python语句后,查看数据库是否有写入数据。如果有的话,你就完成了。

  

  在此处查看完整代码:

  # 导入相关联的包 import requests import time import random import socket import http.client import pymysql from bs4 import BeautifulSoup import csv def getContent(url , data = None):  header={  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',  'Accept-Encoding': 'gzip, deflate, sdch',  'Accept-Language': 'zh-CN,zh;q=0.8',  'Connection': 'keep-alive',  'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'  } # request 的请求头  timeout = random.choice(range(80, 180))  while True:  try:  rep = requests.get(url,headers = header,timeout = timeout) #请求url地址,获得返回 response 信息  rep.encoding = 'utf-8'  break  except socket.timeout as e: # 以下都是异常处理  print( '3:', e)  time.sleep(random.choice(range(8,15)))  except socket.error as e:  print( '4:', e)  time.sleep(random.choice(range(20, 60)))  except http.client.BadStatusLine as e:  print( '5:', e)  time.sleep(random.choice(range(30, 80)))  except http.client.IncompleteRead as e:  print( '6:', e)  time.sleep(random.choice(range(5, 15)))  print('request success')  return rep.text # 返回的 Html 全文 def getData(html_text):  final = []  bs = BeautifulSoup(html_text, "html.parser") # 创建BeautifulSoup对象  body = bs.body #获取body  data = body.find('div',{'id': '7d'})  ul = data.find('ul')  li = ul.find_all('li')  for day in li:  temp = []  date = day.find('h1').string  temp.append(date) #添加日期  inf = day.find_all('p')  weather = inf[0].string #天气  temp.append(weather)  temperature_highest = inf[1].find('span').string #***温度  temperature_low = inf[1].find('i').string # ***温度  temp.append(temperature_highest)  temp.append(temperature_low)  final.append(temp)  print('getDate success')  return final def writeData(data, name):  with open(name, 'a', errors='ignore', newline='') as f:  f_csv = csv.writer(f)  f_csv.writerows(data)  print('write_csv success') def createTable():  # 打开数据库连接  db = pymysql.connect("localhost", "zww", "960128", "test")  # 使用 cursor() 方法创建一个游标对象 cursor  cursor = db.cursor()  # 使用 execute() 方法执行 SQL 查询  cursor.execute("SELECT VERSION()")  # 使用 fetchone() 方法获取单条数据.  data = cursor.fetchone()  print("Database version : %s " % data) # 显示数据库版本(可忽略,作为个栗子)  # 使用 execute() 方法执行 SQL,如果表存在则删除  cursor.execute("DROP TABLE IF EXISTS WEATHER")  # 使用预处理语句创建表  sql = """CREATE TABLE WEATHER (  w_id int(8) not null primary key auto_increment,   w_date varchar(20) NOT NULL ,  w_detail varchar(30),  w_temperature_low varchar(10),  w_temperature_high varchar(10)) DEFAULT CHARSET=utf8"""  cursor.execute(sql)  # 关闭数据库连接  db.close()  print('create table success') def insertData(datas):  # 打开数据库连接  db = pymysql.connect("localhost", "zww", "960128", "test")  # 使用 cursor() 方法创建一个游标对象 cursor  cursor = db.cursor()  try:  # 批量插入数据  cursor.executemany('insert into WEATHER(w_id, w_date, w_detail, w_temperature_low, w_temperature_high) value(null, %s,%s,%s,%s)', datas)  # 提交到数据库执行  db.commit()  except Exception as e:  print('插入时发生异常' + e)  # 如果发生错误则回滚  db.rollback()  # 关闭数据库连接  db.close()  print('insert data success') if __name__ == '__main__':  url ='http://www.weather.com.cn/weather/101210101.shtml'  html = getContent(url) # 获取网页信息  result = getData(html) # 解析网页信息,拿到需要的数据  writeData(result, 'D:/py_work/venv/Include/weather.csv') #数据写入到 csv文档中  # createTable() #表创建一次就好了,注意  insertData(result) #批量写入数据  print('my frist python file')  

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线