数据解析-正则表达式

常用正则表达式回顾

正则练习

  1. import re
  2. #提取出python
  3. key="javapythonc++php"
  4. re.findall('python',key)[0]
  5. #####################################################################
  6. #提取出hello world
  7. key="

    hello world

    "

  8. re.findall('

    (.*)

    ',key)[0]

  9. #####################################################################

  10. #提取170

  11. string = '我喜欢身高为170的女孩'

  12. re.findall('\d+',string)

  13. #####################################################################

  14. #提取出http://和https://

  15. key='http://www.baidu.com and https://boob.com'

  16. re.findall('https?://',key)

  17. #####################################################################

  18. #提取出hello

  19. key='lalalahellohahah' #输出hello

  20. re.findall('<[Hh][Tt][mM][lL]>(.*)',key)

  21. #####################################################################

  22. #提取出hit.

  23. key='bobo@hit.edu.com'#想要匹配到hit.

  24. re.findall('h.*?\.',key)

  25. #####################################################################

  26. #匹配sas和saas

  27. key='saas and sas and saaas'

  28. re.findall('sa{1,2}s',key)

项目需求:爬取糗事百科指定页面的糗图,并将其保存到指定文件夹中

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import requests
  4. import re
  5. import os
  6. if __name__ == "__main__":
  7. url = 'https://www.qiushibaike.com/pic/%s/'
  8. headers={
  9. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
  10. }
  11. #指定起始也结束页码
  12. page_start = int(input('enter start page:'))
  13. page_end = int(input('enter end page:'))
  14. #创建文件夹
  15. if not os.path.exists('images'):
  16. os.mkdir('images')
  17. #循环解析且下载指定页码中的图片数据
  18. for page in range(page_start,page_end+1):
  19. print('正在下载第%d页图片'%page)
  20. new_url = format(url % page)
  21. response = requests.get(url=new_url,headers=headers)
  22. #解析response中的图片链接
  23. e = '
    .*?.*?
    '
  24. pa = re.compile(e,re.S)
  25. image_urls = pa.findall(response.text)
  26. #循环下载该页码下所有的图片数据
  27. for image_url in image_urls:
  28. image_url = 'https:' + image_url
  29. image_name = image_url.split('/')[-1]
  30. image_path = 'images/'+image_name
  31. image_data = requests.get(url=image_url,headers=headers).content
  32. with open(image_path,'wb') as fp:
  33. fp.write(image_data)
posted @ 2021-03-22 13:44  好吗,好  阅读(81)  评论(0)    收藏  举报