正则表达式爬虫应用(校花网)

 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命令就能有效的完成我们需要的操作。

subprocess模块允许一个进程创建一个新的子进程,通过管道连接到子进程的stdin/stdout/stderr,获取子进程的返回值等操作。
这个模块只一个类: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模块的更多相关文章

  1. Python开发基础-Day14正则表达式和re模块

    正则表达式 就其本质而言,正则表达式(或 re)是一种小型的.高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现.正则表达式模式被编译成一系列的字节码,然后由用 ...

  2. configparser模块,subprocess 模块,xlrd,xlwt ,xml 模块,面向对象

    1. configparser模块 2.subprocess 模块 3.xlrd,xlwt 4.xml 模块 5.面向对象 面向对象是什么? 是一种编程思想,指导你如何更好的编写代码 关注点在对象 具 ...

  3. [xml模块、hashlib模块、subprocess模块、os与sys模块、configparser模块]

    [xml模块.hashlib模块.subprocess模块.os与sys模块.configparser模块] xml模块 XML:全称 可扩展标记语言,为了能够在不同的平台间继续数据的交换,使交换的数 ...

  4. python重要模块之subprocess模块

    python重要模块之subprocess模块 我们经常要通过python去执行系统的命令或者脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就相当于发起了一个新的进程, ...

  5. python基础之正则表达式爬虫应用,configparser模块和subprocess模块

    正则表达式爬虫应用(校花网) 1 import requests 2 import re 3 import json 4 #定义函数返回网页的字符串信息 5 def getPage_str(url): ...

  6. 还在用Alpine作为你Docker的Python开发基础镜像?其实Ubuntu更好一点

    原文转载自「刘悦的技术博客」https://v3u.cn/a_id_173 一般情况下,当你想为你的Python开发环境选择一个基础镜像时,大多数人都会选择Alpine,为什么?因为它太小了,仅仅只有 ...

  7. Python开发基础-Day13模块2

    sys模块 sys模块提供了一系列有关Python运行环境的变量和函数. #重点记忆 sys.argv #命令行参数List,第一个元素是程序本身路径 sys.exit(n) #退出执行的程序未见,正 ...

  8. python常用模块补充hashlib configparser logging,subprocess模块

    一.hashlib模板 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定 ...

  9. os模块、os.path模块、shutil模块、configparser模块、subprocess模块

    一.os模块 os指的是操作系统 该模块主要用于处理与操作系统相关的操作,常用的是文件操作(读.写.删.复制.重命名). os.getcwd()  获取当前文件所在的文件夹路径 os.chdir()  ...

随机推荐

  1. tomcat优化总结【持续更新】

    配置优化 <Connector port=" maxThreads=" URIEncoding="UTF-8" maxKeepAliveRequests= ...

  2. Eclipse Tomcat Project报错:HTTP Status 404错误

    想要在eclipse里部署tomcat,结果tomcat单独可以通过连接测试,用eclipse就404了 404肯定都是目录不对,试了半天在eclipse下改了一下配置和文件位置就行了 1.先在菜单栏 ...

  3. 洛谷P2901 [USACO08MAR]牛慢跑Cow Jogging

    题目描述 Bessie has taken heed of the evils of sloth and has decided to get fit by jogging from the barn ...

  4. 【bzoj】1927 [Sdoi2010]星际竞速

    [算法]最小费用最大流 [题解]跟滑雪略有类似,同样因为可以重复所以不是最小路径覆盖. 连向汇的边容量为1足矣,因为一个点只会出去一次(路径结束). bzoj 1927 [Sdoi2010]星际竞速 ...

  5. 报错注入遇到ERROR 1242 (21000): Subquery returns more than 1 row解决方案

    我的SQL语句是这样写的. mysql> select 1,2,3 and updatexml(1,concat(1,(select user from mysql.user),1),1);ER ...

  6. handle_level_irq 与handle_edge_irq 的区别【转】

    转自:http://blog.csdn.net/xavierxiao/article/details/6087277 版权声明:本文为博主原创文章,未经博主允许不得转载. Linux 里, handl ...

  7. 自动化测试===requests+unittest+postman的接口测试

    postman是一个跨平台的接口测试工具,下载链接在这里:https://www.getpostman.com/ unittest是一个单元测试框架,python中安装:pip install uni ...

  8. python基础===【爬虫】爬虫糗事百科首页图片代码

    import requests import re import urllib.request def getHtml(url): page = requests.get(url) html = pa ...

  9. write-ups

    https://github.com/MarioVilas/write-ups https://github.com/Deplorable-Mountaineer/Robot_Dynamite htt ...

  10. 【UOJ#169】元旦老人与数列

    论文题. 考虑到这题的维护和区间操作是反向的,也就是说无法像V那题快速的合并标记. 我们知道,一个区间的最小值和其他值是可以分开来维护的,因为如果一个区间被整体覆盖,那么最小值始终是最小值. 对于被覆 ...