python爬虫三大解析数据方法:正则 及 图片下载案例

基本正则用法回顾

# 提取python
key = 'javapythonc++php'
print(re.findall('python', key)[0])

# 提取hello world
key = '<html><h1>hello world</h1></html>'
print(re.findall('<h1>(hello world)</h1>', key)[0])  # 分组的方法

# 提取170
string = '我喜欢cjv170的身高'
print(re.findall('\d+', string)[0])

# 提取http:// 和 https://
key = 'http://www.baidu.com and https://bjv.com'
print(re.findall('https?', key))  # ?值前面一个字符出现过一次或0次

# 提取hit.
key = '[email protected]'
print(re.findall('h.*?\.', key))  # ?切换贪婪模式

# 提取sas和saas
key = 'saas and sas and saaas'
print(re.findall('sa{1,2}s', key))

# 匹配i开头的行 re.S(单行匹配全部拉通)  re.M(多行匹配)
string = '''fall in love with you
i love you ver much
i love she
i love her'''
print(re.findall('^i.*', string, re.M))

# 匹配全部行
string = '''<div>静夜思
窗前明月光
低头思故乡
</div>'''
print(re.findall('<div>.*</div>', string, re.S))

糗事百科 图片下载案例

import requests
import re

url = 'https://www.qiushibaike.com/pic/'

data = requests.get(url=url).text

 # re.S单行处理 把换行看成\n一起匹配
img_list = re.findall('<div class="thumb">.*?<img src="//(.*?)".*?>.*?</div>', data, re.S) 

for url in img_list:
    img_url = 'https://' + url
    img_name = url.split('/')[-1]
    img_data = requests.get(url=img_url).content  # 图片二进制
    with open('糗事百科图片库/'+img_name, 'wb') as f:
        f.write(img_data)

猜你喜欢

转载自blog.csdn.net/weixin_42329277/article/details/84074787
今日推荐