python:今日头条中街拍美图的爬取

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yk_0311/article/details/82532747
# 网页地址:https://www.toutiao.com/search/?keyword=%E8%A1%97%E6%8B%8D
import requests
from bs4 import BeautifulSoup
import re
import os


def getPage_json(page):
    url = 'https://www.toutiao.com/search_content/?'
    hd = {'User-Agent': 'Mozilla/5.0'}
    params = {'offset': page,
              'format': 'json',
              'keyword': '街拍',  # 不能写%E8%A1%97%E6%8B%8D
              'autoload': 'true',
              'count': '20',
              'cur_tab': '3',
              'from': 'gallery'
              }
    try:
        r = requests.get(url, headers=hd, params=params)
        r.raise_for_status()  # 抛出异常
        r.encoding = r.apparent_encoding  # 编码
        # print(r.json())
        return r.json()
    except:
        print("请求出错1")


def get_article_URL(json):  # 找到article_url
    if json.get('data'):  # 如果数据为真
        for item in json.get('data'):  # json.get('data')返回的是一个列表
            if item == None:
                continue
            yield item.get('article_url')


# get_article_URL(getPage(0))
def get_article_URL_HTML(url):  # 将article_url输入,得到HTML页面
    hd = {'User-Agent': 'Mozilla/5.0'}
    try:
        r = requests.get(url, headers=hd)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        print('请求出错2')


def parse_HTML(html):  # 分析HTM页面得到图片的url
    try:
        # soup = BeautifulSoup(html, 'html.parser')
        # title = soup.select('title')[0].get_text()  # 使用CSS选择器,调用select()方法获取标题
        # print(title)
        image_pattern = re.compile('gallery: (.*?),\n', re.S)  # 图片的链接在之中,使用正则表达式匹配
        result = re.search(image_pattern, html)
        if result:
            result = result.group(1)
            result = result[12:-2]
            result = re.sub(r'\\', '', result)  # 将字符串中的\\替换,便于后续操作
            # print(result)测试
            ls = re.findall(r'"http://p\w.*?"', result)  # 在字符串中匹配到到链接

            '''
            会匹配到如下数据
            ['"http://p3.pstatp.com/origin/pgc-image/15363442103372ba41b3a6e"']
            需将最外层的单引号去掉
            '''

            # 链接会有重复,所以进行筛选
            ulist = []
            ulist.append(eval(ls[0]))
            for i in range(len(ls)):
                if ulist[-1][-5:] != eval(ls[i])[-5:]:
                    ulist.append(eval(ls[i]))
            # 这样子我们就得到了图片的url,并且存储在了ulist中
            return ulist
    except:
        pass


def saveimages(ulist):
    root = 'D://IDE\Pycharm//《网络爬虫实战开发》//Ajax结果提取//images'
    hd = {'User-Agent': 'Mozilla/5.0'}
    if not os.path.exists(root):  # 如果根目录不存在就创建一个
        os.mkdir(root)
    try:
        for imageurl in ulist:
            # print(imageurl)测试
            path = root + '//' + imageurl.split('/')[-1] + '.jpg'
            if not os.path.exists(path):  # 其实这一句话其实不用写,因为在parse_HTML中已经筛选过链接了,就不会存在重复了
                r = requests.get(imageurl, headers=hd)
                r.raise_for_status()
                with open(path, 'wb') as f:
                    f.write(r.content)
    except:
        print('请求错误3')


def main():
    for offset in range(0, 20, 20):
        json = getPage_json(offset)
        article_urls = get_article_URL(json)
        for url in article_urls:
            # print(url)测试
            urlList = parse_HTML(get_article_URL_HTML(url))  # 返回图片url的列表
            # print(urlList)测试
            saveimages(urlList)


main()

《python3网络爬虫开发实战》中代码已经不管用了

猜你喜欢

转载自blog.csdn.net/Yk_0311/article/details/82532747