Python开发基础-Day15正则表达式爬虫应用,configparser模块和subprocess模块
正则表达式爬虫应用(校花网)
import requests
import re
import json
#定义函数返回网页的字符串信息
def getPage_str(url):
page_string=requests.get(url)
return page_string.text hua_dic={}
def run_re(url): #爬取名字、学校和喜爱的人数
hua_str=getPage_str(url)
hua_list=re.finditer('<span class="price">(?P<name>.*?)</span>.*?class="img_album_btn">(?P<school>.*?)</a>.*?<em class.*?>(?P<like>\d+?)</em>',hua_str,re.S)
for n in hua_list: #将名字、学校和喜爱的人数写入字典
hua_dic[n.group('name')]=[n.group('school'),n.group('like')] def url(): #获取url地址
for i in range(0,43):
urls="http://www.xiaohuar.com/list-1-%s.html" %i
yield urls
#执行爬取内容
for i in url():
run_re(i) print(hua_dic) # with open('aaa','w',encoding='utf-8') as f:
# f.write(str(hua_dic))
data=json.dumps(hua_dic) #将爬取的字典进行序列化操作
print(data)
f=open('hua.json','a')
f.write(data)
#反序列化
# f1=open('hua.json','r')
# new_data=json.load(f1)
# print(new_data)
configparser模块
该模块适用于linux下conf配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
如:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no
生成文件示例:
import configparser
config = configparser.ConfigParser() #定义一个对象
config["DEFAULT"] = {'ServerAliveInterval': '', #定义DEFAULT节的键值对信息,DEFAULT节是一个特殊的节,在其他的节里都包含DEFAULT节的内容
'Compression': 'yes',
'CompressionLevel': '',
'ForwardX11':'yes'
}
config['bitbucket.org'] = {'User':'hg'} #普通的节
config['topsecret.server.com'] = {'Host Port':'','ForwardX11':'no'} #普通的节
with open('example.ini', 'w') as configfile: #写入文件
config.write(configfile)
注:会忽略大小写,全部写入小写
打开文件,加载文件内容
config = configparser.ConfigParser() #创建对象
print(config.sections()) #直接读取内容会读取不到内容
config.read('example.ini')
print(config.sections())
查找内容:
#判断文件内是否包含一个节
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True
print(config.has_section('bitbucket.org')) #True #判断一个节中是否包含一个键
print(config.has_option('bitbucket.org','user')) #获取一个节里的一个键的值
print(config.get('bitbucket.org','user'))
print(config['bitbucket.org']["user"]) # hg #获取一个节里的所有键
for key in config['bitbucket.org']: # 注意,有default会默认default的键
print(key)
print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键 #以元组方式获取一个节里所有的键值对
print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有键值对
修改内容:
# 添加一个节点,添加一个键值
config.add_section("SEC_1") #添加一个节
config['SEC_1']["user"]='bob' #在一个节中添加一个键值对
config.write(open('example.ini', 'w')) # 删除一个节点,删除一个键值
config.remove_option("SEC_1",'User') #删除一个节中的一个键值对
config.remove_section("SEC_1") #删除一个节
config.write(open('example.ini', 'w'))
subprocess模块
当我们需要调用系统的命令的时候,最先考虑的os模块。用os.system()和os.popen()来进行操作。但是这两个命令过于简单,不能完成一些复杂的操作,如给运行的命令提供输入或者读取命令的输出,判断该命令的运行状态,管理多个命令的并行等等。这时subprocess中的Popen命令就能有效的完成我们需要的操作。
import subprocess
# 创建一个新的进程,与主进程不同步 if in win:
s=subprocess.Popen('dir',shell=True)
# 创建一个新的进程,与主进程不同步 if in linux:
s=subprocess.Popen('ls')
s.wait() # s是Popen的一个实例对象,意思是等待子进程运行完后才继续运行
print('ending...')
带选项命令(win、linux一样)
import subprocess
subprocess.Popen('ls -l',shell=True)
#subprocess.Popen(['ls','-l'])
控制子进程
s.poll() # 检查子进程状态
s.kill() # 终止子进程
s.send_signal() # 向子进程发送信号
s.terminate() # 终止子进程
s.pid:子进程号
子进程输出流控制
可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):
import subprocess
# s1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
# print(s1.stdout.read())
#s2.communicate()
s1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)
s2 = subprocess.Popen(["grep","0:0"],stdin=s1.stdout, stdout=subprocess.PIPE)
out = s2.communicate()
print(out) s=subprocess.Popen("dir",shell=True,stdout=subprocess.PIPE)
print(s.stdout.read().decode("gbk"))
ubprocess.PIPE实际上为文本流提供一个缓存区。s1的stdout将文本输出到缓存区,随后s2的stdin从该PIPE中将文本读取走。s2的输出文本也被存放在PIPE中,直到communicate()方法从PIPE中读取出PIPE中的文本。
注意:communicate()是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成
Python开发基础-Day15正则表达式爬虫应用,configparser模块和subprocess模块的更多相关文章
- Python开发基础-Day14正则表达式和re模块
正则表达式 就其本质而言,正则表达式(或 re)是一种小型的.高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现.正则表达式模式被编译成一系列的字节码,然后由用 ...
- configparser模块,subprocess 模块,xlrd,xlwt ,xml 模块,面向对象
1. configparser模块 2.subprocess 模块 3.xlrd,xlwt 4.xml 模块 5.面向对象 面向对象是什么? 是一种编程思想,指导你如何更好的编写代码 关注点在对象 具 ...
- [xml模块、hashlib模块、subprocess模块、os与sys模块、configparser模块]
[xml模块.hashlib模块.subprocess模块.os与sys模块.configparser模块] xml模块 XML:全称 可扩展标记语言,为了能够在不同的平台间继续数据的交换,使交换的数 ...
- python重要模块之subprocess模块
python重要模块之subprocess模块 我们经常要通过python去执行系统的命令或者脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就相当于发起了一个新的进程, ...
- python基础之正则表达式爬虫应用,configparser模块和subprocess模块
正则表达式爬虫应用(校花网) 1 import requests 2 import re 3 import json 4 #定义函数返回网页的字符串信息 5 def getPage_str(url): ...
- 还在用Alpine作为你Docker的Python开发基础镜像?其实Ubuntu更好一点
原文转载自「刘悦的技术博客」https://v3u.cn/a_id_173 一般情况下,当你想为你的Python开发环境选择一个基础镜像时,大多数人都会选择Alpine,为什么?因为它太小了,仅仅只有 ...
- Python开发基础-Day13模块2
sys模块 sys模块提供了一系列有关Python运行环境的变量和函数. #重点记忆 sys.argv #命令行参数List,第一个元素是程序本身路径 sys.exit(n) #退出执行的程序未见,正 ...
- python常用模块补充hashlib configparser logging,subprocess模块
一.hashlib模板 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定 ...
- os模块、os.path模块、shutil模块、configparser模块、subprocess模块
一.os模块 os指的是操作系统 该模块主要用于处理与操作系统相关的操作,常用的是文件操作(读.写.删.复制.重命名). os.getcwd() 获取当前文件所在的文件夹路径 os.chdir() ...
随机推荐
- nginx 安装 lua-nginx-module
nginx增加lua模块 yum install -y gcc g++ gcc-c++ zlib zlib-devel openssl openssl-devel pcre pcre-devel wg ...
- mysql数据库cmd直接登录
找到mysql的安装路径: 将该路径配置到环境变量中: win+R代开dos窗口:输入mysql -uroot -p回车,输入密码.
- 【bzoj3362-导航难题】带权并查集
题意: 约翰所在的乡村可以看做一个二维平面,其中有N 座牧场,每座牧场都有自己的坐标,编号为1到N.牧场间存在一些道路,每条道路道路连接两个不同的牧场,方向必定平行于X 轴或Y轴.连通两座牧场之间的路 ...
- 所有和Java中代理有关的知识点都在这了。
对于每一个Java开发来说,代理这个词或多或少都会听说过.你可能听到过的有代理模式.动态代理.反向代理等.那么,到底什么是代理,这么多代理又有什么区别呢.本文就来简要分析一下. 代理技术,其实不只是J ...
- John's trip(POJ1041+欧拉回路+打印路径)
题目链接:http://poj.org/problem?id=1041 题目: 题意:给你n条街道,m个路口,每次输入以0 0结束,给你的u v t分别表示路口u和v由t这条街道连接,要输出从起点出发 ...
- POj 2104 K-th Number (分桶法+线段树)
题目链接 Description You are working for Macrohard company in data structures department. After failing ...
- Python 关于时间和日期函数使用 -- (转)
python中关于时间和日期函数有time和datatime 1.获取当前时间的两种方法: import datetime,time now = time.strftime("%Y-%m ...
- linux系统引导流程
1.固件:硬件和软件结合.加电自检是我们按下电源会检测硬件像cpu.内存.网卡等信息.(从硬件层次检测硬件是否可用) 固件设置实例:设置时间 软件时间和硬件时间: [root@VM_0_12_cent ...
- Git常规配置与基本用法
Git环境配置 一. 全局配置 1. 配置文件 git全局配置文件.gitconfig默认在当前系统用户文件夹下,window可运行%USERPROFILE%查找,Mac系统在cd ~查找. 具体配置 ...
- Python Matplotlib图表汉字显示成框框的解决办法
http://blog.sina.com.cn/s/blog_662dcb820102vu3d.html http://blog.csdn.net/fyuanfena/article/details/ ...