Day27正則表達式爬蟲應用,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': '45',  #定義DEFAULT節的鍵值對信息,DEFAULT節是一個特殊的節,在其他的節裏都包含DEFAULT節的內容
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }

config['bitbucket.org'] = {'User':'hg'}  #普通的節

config['topsecret.server.com'] = {'Host Port':'5022','ForwardX11':'no'}  #普通的節

with open('example.ini', 'w') as configfile:  #寫入文件
    config.write(configfile)

查找文件內容:

import configparser

config = configparser.ConfigParser()
#--------------------------查找文件內容,基於字典的形
print(config.sections())        #  []
config.read('example.ini')
print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True

print(config['bitbucket.org']["user"])  # hg
print(config['DEFAULT']['Compression']) #yes
print(config['topsecret.server.com']['ForwardX11'])  #no
print(config['bitbucket.org'])          #<Section: bitbucket.org>
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'下所有鍵值對
print(config.get('bitbucket.org','compression')) # yes       get方法取深層嵌套的值

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一樣)
1 import subprocess
2 subprocess.Popen(‘ls -l’,shell=True)
3 #subprocess.Popen([‘ls’,’-l’])
控制子進程

1 s.poll() # 檢查子進程狀態
2 s.kill() # 終止子進程
3 s.send_signal() # 向子進程發送信號
4 s.terminate() # 終止子進程
5 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對象的一個方法,該方法會阻塞父進程,直到子進程完成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章