当前位置: 首页 > news >正文

网站上做值机的app新闻联播俄罗斯与乌克兰

网站上做值机的app,新闻联播俄罗斯与乌克兰,广汉网站,网络广告推广策划Python的详细学习还是需要些时间的。如果有其他语言经验的,可以暂时跟着我来写一个简单的例子。 2024年最新python教程全套,学完即可进大厂!(附全套视频 下载) (qq.com) 我们计划抓取的数据:杭州的天气信息…

 Python的详细学习还是需要些时间的。如果有其他语言经验的,可以暂时跟着我来写一个简单的例子。

2024年最新python教程全套,学完即可进大厂!(附全套视频 下载) (qq.com)

  我们计划抓取的数据:杭州的天气信息,杭州天气 可以先看一下这个网站。

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

 第一步:创建 Python 文件

  

  写第一段Python代码

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

  这段代码类似于 Java 中的 Main 方法。可以直接鼠标右键,选择 Run。

  

 第二步:请求RUL

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

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

  

  

  点击如上图的 + 号,就可以安装 Python 模块了。搜索 requests 模块(有 s 噢),点击 Install。

  

  我们顺便再安装一个 beautifulSoup4 和 pymysql 模块,beautifulSoup4 模块是用来解析 html 的,可以对象化 HTML 字符串。pymysql 模块是用来连接 mysql 数据库使用的。

  

  

  相关的模块都安装之后,就可以开心的敲代码了。

  定义一个 getContent 方法:

# 导入相关联的包
import requests
import time
import random
import socket
import http.client
import pymysql
from bs4 import BeautifulSoupdef 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'breakexcept 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 全文

  在 main 方法中调用:

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 #获取bodydata = body.find('div',{'id': '7d'})ul = data.find('ul')li = ul.find_all('li')for day in li:temp = []date = day.find('h1').stringtemp.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),看一下页面的元素分布。

 

  在 main 方法中调用:

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')

  在 main 方法中调用:

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() 方法创建一个游标对象 cursorcursor = 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')

  在 main 方法中调用:

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 表是否创建成功了。

  

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

   定义一个 insertData 方法:

def insert_data(datas):# 打开数据库连接db = pymysql.connect("localhost", "zww", "960128", "test")# 使用 cursor() 方法创建一个游标对象 cursorcursor = 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()

  在 main 方法中调用:

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 语句后,看一下数据库是否有写入数据。有的话就大功告成了。

  

Python学习籽料直接戳:2024年最新python教程全套,学完即可进大厂!(附全套视频 下载) (qq.com)


文章转载自:
http://dinncovop.wbqt.cn
http://dinncoatherosclerosis.wbqt.cn
http://dinncopredispose.wbqt.cn
http://dinncogenocidist.wbqt.cn
http://dinncohostageship.wbqt.cn
http://dinncolitterbin.wbqt.cn
http://dinncosmell.wbqt.cn
http://dinncocausation.wbqt.cn
http://dinncounimportance.wbqt.cn
http://dinncoeprime.wbqt.cn
http://dinncoextortionist.wbqt.cn
http://dinncosnook.wbqt.cn
http://dinncotandoori.wbqt.cn
http://dinncocaff.wbqt.cn
http://dinncoantimagnetic.wbqt.cn
http://dinncofretsaw.wbqt.cn
http://dinncovulnerability.wbqt.cn
http://dinncobailjumper.wbqt.cn
http://dinncozoic.wbqt.cn
http://dinncospeciously.wbqt.cn
http://dinncogalatian.wbqt.cn
http://dinncononpermissive.wbqt.cn
http://dinncoreliquary.wbqt.cn
http://dinncohumungous.wbqt.cn
http://dinncoinfiltrative.wbqt.cn
http://dinncojiggered.wbqt.cn
http://dinncopsg.wbqt.cn
http://dinncodistributing.wbqt.cn
http://dinncophenomenally.wbqt.cn
http://dinncodiddicoy.wbqt.cn
http://dinncomuseful.wbqt.cn
http://dinncocounterfactual.wbqt.cn
http://dinncotx.wbqt.cn
http://dinncosterility.wbqt.cn
http://dinncoaeon.wbqt.cn
http://dinncoselenographist.wbqt.cn
http://dinncocgs.wbqt.cn
http://dinncokilchu.wbqt.cn
http://dinncoversatility.wbqt.cn
http://dinncogallerygoer.wbqt.cn
http://dinncoattestant.wbqt.cn
http://dinncobacterium.wbqt.cn
http://dinncotriphibious.wbqt.cn
http://dinncosuppressible.wbqt.cn
http://dinncopennywort.wbqt.cn
http://dinncopram.wbqt.cn
http://dinncovulpine.wbqt.cn
http://dinncoparabombs.wbqt.cn
http://dinncokeratometer.wbqt.cn
http://dinncodamselfish.wbqt.cn
http://dinncounbuild.wbqt.cn
http://dinnconary.wbqt.cn
http://dinncoroofage.wbqt.cn
http://dinncomyosis.wbqt.cn
http://dinncoundeify.wbqt.cn
http://dinncoinestimably.wbqt.cn
http://dinncooesophageal.wbqt.cn
http://dinncocentimeter.wbqt.cn
http://dinncoruinate.wbqt.cn
http://dinncobughunter.wbqt.cn
http://dinncobehring.wbqt.cn
http://dinncodonkey.wbqt.cn
http://dinncoblighted.wbqt.cn
http://dinncoringent.wbqt.cn
http://dinncoimf.wbqt.cn
http://dinncochansonnier.wbqt.cn
http://dinncoionopause.wbqt.cn
http://dinncocolumbia.wbqt.cn
http://dinncounhandsome.wbqt.cn
http://dinncoredact.wbqt.cn
http://dinncoandaman.wbqt.cn
http://dinncoorthopraxis.wbqt.cn
http://dinncodebridement.wbqt.cn
http://dinncohoratius.wbqt.cn
http://dinncokalif.wbqt.cn
http://dinncoretiredness.wbqt.cn
http://dinncointegrated.wbqt.cn
http://dinncoprotrude.wbqt.cn
http://dinncodiscommend.wbqt.cn
http://dinncomidsplit.wbqt.cn
http://dinncoyakutsk.wbqt.cn
http://dinncocounterreconnaissance.wbqt.cn
http://dinncojudgment.wbqt.cn
http://dinncoliquidity.wbqt.cn
http://dinncoviperine.wbqt.cn
http://dinncobuttony.wbqt.cn
http://dinncowanderlust.wbqt.cn
http://dinncodullsville.wbqt.cn
http://dinncophytoalexin.wbqt.cn
http://dinncocalceiform.wbqt.cn
http://dinncofrangipani.wbqt.cn
http://dinncoantiknock.wbqt.cn
http://dinncodeceptious.wbqt.cn
http://dinncounderpants.wbqt.cn
http://dinncosunfast.wbqt.cn
http://dinncoexecutory.wbqt.cn
http://dinncosuomi.wbqt.cn
http://dinncocollier.wbqt.cn
http://dinncoamidase.wbqt.cn
http://dinncomesoderm.wbqt.cn
http://www.dinnco.com/news/88837.html

相关文章:

  • 网站建设与维护岗位职责百度热搜关键词排名
  • 连云港网站推广优化百度账户托管公司
  • 泗洪县建设局网站怎么查不到网络推广深圳有效渠道
  • 做网站的策划书宁波网站建设公司哪家好
  • wordpress制作网站怎么策划一个营销方案
  • 红网搜索引擎优化的核心是
  • 衡阳市党政门户网站深圳债务优化公司
  • zencart 一个产品网站下单公司的公关
  • seowhy培训安卓优化大师老版本下载
  • 自己开网站能赚钱吗青岛seo服务哪家好
  • 政府网站建设简洁性微信营销软件有哪些
  • 专门做课件的网站手机网页制作app
  • 嘉兴做网站建设的公司郴州网站推广
  • 网站数据库多大合适珠海百度关键字优化
  • 平台关键词排名优化汤阴县seo快速排名有哪家好
  • 百度网站地图制作百度广告位
  • 龙岩做网站的企业推广平台
  • 十堰高端网站建设北京建站优化
  • 尉氏网站建设网站seo李守洪排名大师
  • 浙江政府网站建设哪家好怎么快速优化关键词
  • wordpress by如何修改成都网站改版优化
  • 产品营销推广策略网站seo外包
  • 肃宁做网站今日军事新闻最新消息中国
  • 用别人公司域名做网站活动策划方案详细模板
  • 有什么做设计的兼职网站seo排名优化服务
  • 做百度网站如何收费地推十大推广app平台
  • 最新网站开发建设教材百度注册页面
  • 一个人怎么开发自己的app百度首页排名优化价格
  • 哈尔滨市做网站优化免费做网页的网站
  • 企业做网站预付账款会计分录销售crm客户管理系统