python爬虫正则解析例子

# Author: Sooele

import re
#匹配i开头
string = '''fall in love with you
i love you very much
i love she
i love her'''

text = re.findall('^i.*',string,re.M)

print(text)
#匹配全部行
import re
string1 = """细思极恐
你的队友在看书
你的敌人在磨刀
你的闺蜜在减肥
隔壁老王在练腰
"""
text = re.findall('.*',string1,re.S)
print(text)
#爬取糗事百科中所有的图片进行保存
#%%
import requests
import re
import urllib
import os
#%%
url = 'https://www.qiushibaike.com/pic/page/%d/?s=5170552'
# page = 1
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
}
if not os.path.exists('./qiutu'):
    os.mkdir('./qiutu')
    
start_page = int(input('enter a start pageNum:'))
end_page = int(input('enter a end pageNum:'))

for page in range(start_page,end_page+1):
    new_url = format(url%page)
#     print(new_url)
    page_text = requests.get(url=new_url,headers=headers).text
    img_url_list = re.findall('<div class="thumb">.*?<img src="(.*?)" alt=.*?</div>',page_text,re.S)
    for img_url in img_url_list:
        img_url = 'https:'+img_url
        imgName = img_url.split('/')[-1]
        imgPath = 'qiutu/'+imgName
        urllib.request.urlretrieve(url=img_url,filename=imgPath)
        print(imgPath,'下载成功!')
        
print('over!!!')

说点什么

avatar
  Subscribe  
提醒