吴裕雄 python 爬虫(3)
- import hashlib
- md5 = hashlib.md5()
- md5.update(b'Test String')
- print(md5.hexdigest())
- import hashlib
- md5 = hashlib.md5(b'Test String').hexdigest()
- print(md5)
- import os
- import hashlib
- import requests
- # url = "http://opendata.epa.gov.tw/ws/Data/REWXQA/?$orderby=SiteName&$skip=0&$top=1000&format=json"
- url = "https://www.baidu.com"
- # 读取网页原始码
- html=requests.get(url).text.encode('utf-8-sig')
- # 判断网页是否更新
- md5 = hashlib.md5(html).hexdigest()
- if os.path.exists('F:\\pythonBase\\pythonex\\ch06\\old_md5.txt'):
- with open('F:\\pythonBase\\pythonex\\ch06\\old_md5.txt', 'r') as f:
- old_md5 = f.read()
- with open('F:\\pythonBase\\pythonex\\ch06\\old_md5.txt', 'w') as f:
- f.write(md5)
- else:
- with open('F:\\pythonBase\\pythonex\\ch06\\old_md5.txt', 'w') as f:
- f.write(md5)
- if md5 != old_md5:
- print('数据已更新...')
- else:
- print('数据未更新,从数据库读取...')
- import os
- import ast
- import hashlib
- import sqlite3
- import requests
- from bs4 import BeautifulSoup
- conn = sqlite3.connect('F:\\pythonBase\\pythonex\\DataBasePM25.sqlite') # 建立数据库连接
- cursor = conn.cursor() # 建立 cursor 对象
- # 建立一个数据表
- sqlstr='''
- CREATE TABLE IF NOT EXISTS TablePM25 ("no" INTEGER PRIMARY KEY AUTOINCREMENT
- NOT NULL UNIQUE ,"SiteName" TEXT NOT NULL ,"PM25" INTEGER)
- '''
- cursor.execute(sqlstr)
- url = "http://api.help.bj.cn/apis/aqilist/"
- #html=requests.get(url).text.encode('utf-8-sig') # 读取网页原始码
- html=requests.get(url).text.encode('iso-8859-1').decode('utf-8-sig')
- # print(html)
- html = html.encode('utf-8-sig')
- # 判断网页是否更新
- md5 = hashlib.md5(html).hexdigest()
- old_md5 = ""
- if os.path.exists('F:\\pythonBase\\pythonex\\ch06\\old_md5-.txt'):
- with open('F:\\pythonBase\\pythonex\ch06\\old_md5-.txt', 'r') as f:
- old_md5 = f.read()
- with open('F:\\pythonBase\\pythonex\ch06\\old_md5-.txt', 'w') as f:
- f.write(md5)
- print("old_md5="+old_md5+";"+"md5="+md5) #显示新老md5码进行观察
- if md5 != old_md5:
- print('数据已更新...')
- sp=BeautifulSoup(html,'html.parser') #解析网页内容
- jsondata = ast.literal_eval(sp.text) #此时jscondata取到的是字典类型数据
- # 删除数据表内容
- js1=jsondata.get("aqidata") #取出字典数据中的aqidata项的值(值是列表)
- conn.execute("delete from TablePM25")
- conn.commit()
- n=1
- for city in js1: #city此时是列表js1中的第一条字典数据
- CityName=city["city"] #取出city字典数据中的值为"city"的key
- if(city["pm2_5"] == ""):
- PM25=0
- else: #如果city字典中的key对应的value为空,则PM25=0,否则,把PM25=value
- PM25=int(city["pm2_5"])
- print("城市:{} PM2.5={}".format(CityName,PM25)) #显示城市对应的名称与PM2.5值
- # 新增一笔记录
- sqlstr="insert into TablePM25 values({},'{}',{})" .format(n,CityName,PM25)
- cursor.execute(sqlstr)
- n+=1
- conn.commit() # 主动更新
- else:
- print('数据未更新,从数据库读取...')
- cursor=conn.execute("select * from TablePM25")
- rows=cursor.fetchall()
- for row in rows:
- print("城市:{} PM2.5={}".format(row[1],row[2]))
- conn.close() # 关闭数据库连
........................................................
- import os
- import ast
- import hashlib
- import sqlite3
- import requests
- from bs4 import BeautifulSoup
- # cur_path=os.path.dirname(__file__) # 取得目前路径
- # print(cur_path)
- conn = sqlite3.connect('F:\\pythonBase\\pythonex\\' + 'DataBasePM25.sqlite') # 建立数据库连接
- cursor = conn.cursor() # 建立 cursor 对象
- # 建立一个数据表
- sqlstr='''
- CREATE TABLE IF NOT EXISTS TablePM25 ("no" INTEGER PRIMARY KEY AUTOINCREMENT
- NOT NULL UNIQUE ,"SiteName" TEXT NOT NULL ,"PM25" INTEGER)
- '''
- cursor.execute(sqlstr)
- url = "http://api.help.bj.cn/apis/aqilist/"
- # 读取网页原始码
- # html=requests.get(url).text.encode('utf-8-sig')
- html=requests.get(url).text.encode('iso-8859-1').decode('utf-8-sig')
- # print(html)
- html = html.encode('utf-8-sig')
- print('数据已更新...')
- sp=BeautifulSoup(html,'html.parser') #sp是bs4.Beautifulsoup类
- # 将网页内转换为 list,list 中的元素是 dict
- jsondata = ast.literal_eval(sp.text) #把sp.text字符串转为dict类型
- js=jsondata.get("aqidata") #从jasondata中取出值为"aqidata"的key对应的value的列表
- # 删除数据表内容
- conn.execute("delete from TablePM25")
- conn.commit()
- #把抓到的数据逐条存到数据库
- n=1
- for city in js:
- CityName=city["city"]
- PM25=0 if city["pm2_5"] == "" else int(city["pm2_5"])
- print("城市:{} PM2.5={}".format(CityName,PM25))
- # 新增一条记录
- sqlstr="insert into TablePM25 values({},'{}',{})" .format(n,CityName,PM25)
- cursor.execute(sqlstr)
- n+=1
- conn.commit() # 主动更新
- conn.close() # 关闭数据库连
- from time import sleep
- from selenium import webdriver
- urls = ['http://www.baidu.com','http://www.wsbookshow.com','http://news.sina.com.cn/']
- browser = webdriver.Chrome()
- browser.maximize_window
- for url in urls:
- browser.get(url)
- sleep(3)
- browser.quit()
- from selenium import webdriver #导入webdriver
- url='http://www.wsbookshow.com/bookshow/jc/bk/cxsj/12442.html' #以此链接为例
- browser=webdriver.Chrome() #生成Chrome浏览器对象(结果是打开Chrome浏览器)
- browser.get(url) #在浏览器中打开url
- login_form=browser.find_element_by_id("menu_1") ##查找id="menu_1"的元素
- print(login_form.text) #显示元素内容
- #browser.quit() #退出浏览器,退出驱动程序
- username=browser.find_element_by_name("username") #查找name="username"的元素
- print(username)
- password=browser.find_element_by_name("pwd") #查找name="pwd"的元素
- print(password)
- login_form=browser.find_element_by_xpath("//input[@name='arcID']")
- print(login_form)
- login_form=browser.find_element_by_xpath("//div[@id='feedback_userbox']")
- print(login_form)
- continue_link=browser.find_element_by_link_text('新概念美语')
- print(continue_link)
- continue_link=browser.find_element_by_link_text('英语')
- print(continue_link)
- heading1=browser.find_element_by_tag_name('h1')
- print(heading1)
- content=browser.find_elements_by_class_name('topbanner')
- print(content)
- content=browser.find_elements_by_css_selector('.topsearch')
- print(content)
- # print(content.get_property)
- print()
- browser.quit() #退出浏览器,退出驱动程序
- text = '中华'
- print(type(text))#<class 'str'>
- text1 = text.encode('gbk')
- print(type(text1))#<class 'bytes'>
- print(text1)#b'\xd6\xd0\xbb\xaa'
- text2 = text1.decode('gbk')
- print(type(text2))#<class 'str'>
- print(text2)#中华
- text4= text.encode('utf-8')
- print(type(text4))#<class 'bytes'>
- print(text4)#b'\xe4\xb8\xad\xe5\x8d\x8e'
- text5 = text4.decode('utf-8')
- print(type(text5))#<class 'str'>
- print(text5)#中华
- import requests
- url="http://www.baidu.com"
- response = requests.get(url)
- content = response.text.encode('iso-8859-1').decode('utf-8')
- #把网页源代码解码成Unicode编码,然后用utf-8编码
- print(content)
- from selenium import webdriver # 导入webdriver模块
- chrome_obj = webdriver.Chrome() # 打开Google浏览器
- chrome_obj.get("https://www.baidu.com") # 打开 网址
- print(chrome_obj.title)
- from selenium import webdriver # 导入webdriver模块
- chrome_obj = webdriver.Chrome() # 打开Google浏览器
- chrome_obj.get(r"C:\desktop\text.html") # 打开本地 html页面
吴裕雄 python 爬虫(3)的更多相关文章
- 吴裕雄 python 爬虫(4)
import requests user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, li ...
- 吴裕雄 python 爬虫(2)
import requests from bs4 import BeautifulSoup url = 'http://www.baidu.com' html = requests.get(url) ...
- 吴裕雄 python 爬虫(1)
from urllib.parse import urlparse url = 'http://www.pm25x.com/city/beijing.htm' o = urlparse(url) pr ...
- 吴裕雄--python学习笔记:爬虫基础
一.什么是爬虫 爬虫:一段自动抓取互联网信息的程序,从互联网上抓取对于我们有价值的信息. 二.Python爬虫架构 Python 爬虫架构主要由五个部分组成,分别是调度器.URL管理器.网页下载器.网 ...
- 吴裕雄--python学习笔记:爬虫包的更换
python 3.x报错:No module named 'cookielib'或No module named 'urllib2' 1. ModuleNotFoundError: No module ...
- 吴裕雄--python学习笔记:爬虫
import chardet import urllib.request page = urllib.request.urlopen('http://photo.sina.com.cn/') #打开网 ...
- 吴裕雄 python 神经网络——TensorFlow pb文件保存方法
import tensorflow as tf from tensorflow.python.framework import graph_util v1 = tf.Variable(tf.const ...
- 吴裕雄 python 神经网络——TensorFlow 花瓣分类与迁移学习(4)
# -*- coding: utf-8 -*- import glob import os.path import numpy as np import tensorflow as tf from t ...
- 吴裕雄 python 神经网络——TensorFlow 花瓣分类与迁移学习(3)
import glob import os.path import numpy as np import tensorflow as tf from tensorflow.python.platfor ...
随机推荐
- CS229 6.16 Neurons Networks linear decoders and its implements
Sparse AutoEncoder是一个三层结构的网络,分别为输入输出与隐层,前边自编码器的描述可知,神经网络中的神经元都采用相同的激励函数,Linear Decoders 修改了自编码器的定义,对 ...
- 对KVM虚拟机进行cpu pinning配置的方法
这篇文章主要介绍了对KVM虚拟机进行cpu pinning配置的方法,通过文中的各种virsh命令可进行操作,需要的朋友可以参考下 首先需求了解基本的信息 1 宿主机CPU特性查看 使用virsh n ...
- Web of Science API
Web of Science API是通过Web Service获取Web of Science在线数据的应用程序接口,供各种编程语言调用.简单说,就是你能根据API实时.动态得到网页版Web of ...
- nginx完全关闭log
nginx.conf中要在http一节里面添加 access_log off; error_log off;
- SpringBoot在Kotlin中的实现(二)
根据现在的开发模式和网上的一些资料,SpringBoot需要对业务和操作进行分层,通常分为controller.entity.service.respository等结构.下面以Kotlin官网的例子 ...
- WPF Blend 一个动画结束后另一个动画开始执行(一个一个执行)
先说明思路:一个故事版Storyboard,两个双精度动画帧DoubleAnimation. 一个一个执行的原理:控制动画开始时间(例如第一个动画用时2秒,第二个动画就第2秒起开始执行.) XAML: ...
- 十年阿里java架构师的六大设计原则和项目经验
先看一幅图吧: 这幅图清晰地表达了六大设计原则,但仅限于它们叫什么名字而已,它们具体是什么意思呢?下面我将从原文.译文.理解.应用,这四个方面分别进行阐述. 1.单一职责原则(Single Res ...
- oracle数据库tns配置方法详解
TNS简要介绍与应用 Oracle中TNS的完整定义:transparence Network Substrate透明网络底层,监听服务是它重要的一部分,不是全部,不要把TNS当作只是监听器. TNS ...
- vue生命周期理解图
............................... 它可以总共分为8个阶段: beforeCreate(创建前), created(创建后), beforeMount(载入前), moun ...
- python中的ljust、rjust
ljust()将字符串左对齐右侧填充 rjust()将字符串右对齐左侧填充 举个例子: 1 a = "hello world" 2 a1 = a.ljust(15, "* ...