您好,欢迎来到花图问答。
搜索
您的当前位置:首页Python实战计划学习笔记-爬取商品信息

Python实战计划学习笔记-爬取商品信息

来源:花图问答

结果图###

result.png

代码###

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup

star_alls = []
star_all = []
infos = []
num = 0
path = 'D:/Users/Jessy zhou/Plan-for-combating-master/1_week/1.2 web-element/1.2homework/webpage/index.html'


def getText(item):
    return '' if item == 0 else ''.join(item.get_text())


def getSrc(item):
    return '' if item == 0 else ''.join(item.get('src'))


with open(path, 'r') as web_data:
    soup = BeautifulSoup(web_data.read(), 'html.parser')

    imgs = soup.select('div.thumbnail > img')
    titles = soup.select('div.caption > h4 > a')
    descs = soup.select('div.caption > p')
    prices = soup.select('div.caption > h4.pull-right')
    reviews = soup.select('div.ratings > p.pull-right')
    # stars =soup.select('div.ratings > p:nth-of-type(2)')
    stars = soup.find_all('span', 'glyphicon')

    for star in stars:
        span = str(star)
        if 'empty' in span:
            span_star = span.replace('<span class="glyphicon glyphicon-star-empty"></span>', u'☆')
        else:
            span_star = span.replace('<span class="glyphicon glyphicon-star"></span>', u'★')
        star_alls.append(span_star)
    star_alls = star_alls[2:]
    limit = len(star_alls) / 5
    while num < limit:
        star_all.append(star_alls[num * 5:(num + 1) * 5])
        num += 1

    for img, title, desc, price, review, star_c in zip(imgs, titles, descs, prices, reviews, star_all):
        data = {
            'img': getSrc(img),
            'title': getText(title),
            'desc': getText(desc),
            'price': getText(price),
            'review': getText(review),
            'star': star_c
        }
        infos.append(data)

总结###

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务