爬虫数据解析

一 正则表达式

# 提取出python
key = "javapythonc++php"
re.findall('python', key)

# 提取出hello world
key = "<html><h1>hello word</h1></html>"
re.findall('<h1>(hello word)</h1>', key)

# 提取170
string = '我喜欢身高为170的XX'
re.findall('\d+', string)

# 提取出http://和https://
key = 'http://www.baidu.com and https://boob.com'
re.findall('https?', key)
或
re.findall('https{0,1}', key)

# 提取出hit.
key = '[email protected]'
re.findall('h.*?\.', key) # 贪婪模式:根据正则表达式尽可能多的提取出数据

# 匹配asa和saas
key = 'saas and sas and saaas'
re.findall('sa{1,2}s', key)

# 匹配出i开头的行
string = '''
    fall in love with you
    i love you very much
    i love she
    i love her
    '''
re.findall('^i.*', string, re.M) # re.S(单行匹配) re.M(多行匹配)

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

示例:使用正则对糗事百科中的图片数据进行解析和下载

import requests
import re
import os
headers = {
    #定制请求头中的User-Agent参数,当然也可以定制请求头中其他的参数
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
}
url = 'https://www.qiushibaike.com/imgrank/'
requests.get(url=url, headers=headers)
page_text = response.text

# 数据解析
'''
图片html
<div class="thumb">
    <a href="/article/121733601" target="_blank">
    <img src="//pic.qiushibaike.com/system/pictures/12173/121733601/medium/HDWWXFFANYVPKZGN.jpg" alt="糗事#121733601" class="illustration" width="100%" height="auto">
    </a>
</div>
'''
# 该列表中存储的就是当前页面源码中所有图片链接
img_list = re.findall('<div class="thumb">.*?<img src="(.*?)" .*?>.*?</div>', page_text, re.S)
# 创建一个存储图片数据的文件夹
if not os.path.exists('./imgs'):
    os.mkdir('imgs')

for url in img_list:
    # 将图片的url进行拼接,拼接成一个完整的url
    img_url = 'https:' + url
    # 持久化存储:存储的是图片的数据并不是图片的url
    img_data = requests.get(url=img_url, headers=headers).content
    img_name = url.split('/')[-1]
    img_path = 'imgs/' + img_name
    with open(img_path, 'wb') as fp:
        fp.write(img_data)
        print(img_name+'写入成功')

二  xpath在爬虫的使用流程

下载:pip instal lxml
导包: from lxml import etree

创建etree对象进行制定数据的解析
    - 本地:etree.parse('本地文件路径')
           etree.xpath('xpath表达式')
    - 网络:etree.HTML('网络请求到的页面数据')
           etree.xpath('xpath表达式')

猜你喜欢

转载自www.cnblogs.com/harryblog/p/11325906.html