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() ...
 
随机推荐
- OPENId是什么, OAUTH 是什么
			
what is openId open id is said to be a protocol which uses url as username, so if a website supports ...
 - C# 关于调用微信接口的代码
			
调用微信接口前需要准备的内容. 1.微信公众平台的appid 2.微信公众平台的secret 3..获取tokenid 4.获取ticket 5.生成签名的随机串 6.生成签名的时间戳 7.生成签名 ...
 - .Net MVC4 上传大文件,并保存表单
			
1. 前台 cshtml </pre><pre name="code" class="csharp">@model BLL.BLL.Pr ...
 - Maven学习笔记(一)
			
我们暂且可以把Maven理解成是一个项目构建与依赖管理的工具 为什么选用maven? 约定(惯例)优先原则,默认限定了项目目录结构 提供三方依赖管理(解决了依赖维护的问题) 提供了一致的项目构建管 ...
 - tornado 学习之GET POST方法 -- (转)
			
import torndb import tornado.web import tornado.ioloop from tornado.options import define,options,pa ...
 - net_device->uc_promisc
			
如果设备不支持单播过滤,并且要监听多个单播地址时,就要使用net_device->uc_count和net_device->uc_promisc来设置混杂模式,具体见__dev_set_r ...
 - ERROR: do not initialise statics to false
			
Question about git commit rule I git commit a patch, The patch has a "static int xxxxxxxxxxxxxx ...
 - Linux内核基础--事件通知链(notifier chain)【转】
			
转自:http://blog.csdn.net/wuhzossibility/article/details/8079025 内核通知链 1.1. 概述 Linux内核中各个子系统相互依赖,当其中某个 ...
 - mapper.xml中的<sql>标签
			
原文链接:http://blog.csdn.net/a281246240/article/details/53445547 sql片段标签<sql>:通过该标签可定义能复用的sql语句片段 ...
 - django “如何”系列2:如何编写django-admin 命令
			
应用可以使用manage.py注册自己的动作,例如,你可能想要为你即将发布的应用添加一个manage.py 操作.这节我们将为polls应用添加一个closepoll的命令 添加一个managemen ...