Python爬虫实战第一周作业

1、抓取本地网页解析其中的图片、标题、价格、星级和浏览量

经过查看和分析,每一项都是由一个div包裹

<div class="col-sm-4 col-lg-4 col-md-4">
  <div class="thumbnail">
    <img src="img/pic_0000_073a9256d9624c92a05dc680fc28865f.jpg" alt="">
    <div class="caption">
      <h4 class="pull-right">$24.99</h4>
      <h4>
        <a href="#">EarPod</a></h4>
      <p>See more snippets like this online store item at web store</p>
    </div>
    <div class="ratings">
      <p class="pull-right">65 reviews</p>
      <p>
        <span class="glyphicon glyphicon-star"></span>
        <span class="glyphicon glyphicon-star"></span>
        <span class="glyphicon glyphicon-star"></span>
        <span class="glyphicon glyphicon-star"></span>
        <span class="glyphicon glyphicon-star"></span>
      </p>
    </div>
  </div>
</div>

抓取数据的Python代码#

from bs4 import BeautifulSoup

path = r'G:/1_2_homework_required/index.html'
with open(path,'r') as wb_data:
    soup = BeautifulSoup(wb_data,'lxml')
    imgs = soup.select('div.col-sm-4 > div.thumbnail > img')
    titles = soup.select('div.col-sm-4 > div.thumbnail > div.caption > h4:nth-of-type(2) > a')
    prices = soup.select('div.col-sm-4 > div.thumbnail > div.caption > h4:nth-of-type(1)')
    stars = soup.select('div.col-sm-4 > div.thumbnail > div.ratings > p:nth-of-type(2)')
    views = soup.select('div.col-sm-4 > div.thumbnail > div.ratings > p.pull-right')
    for img,title,price,star,view in zip(imgs,titles,prices,stars,views):
        data = {
            'title' : title.get_text(),
            'img' : img.get('src'),
            'price' : price.get_text(),
            'star' : len(star.find_all('span',class_='glyphicon glyphicon-star')),
            'view' : view.get_text()
        }
        print(data)

这题的难点在于星星数的抓取, 观察发现,每一个星星会有一次
<span class="glyphicon glyphicon-star"></span>
所以统计有多少次,就知道有多少个星星了;

使用find_all 统计有几处是星星的样式,第一个参数定位标签名,第二个参数定位css 样式由于find_all()返回的结果是列表,我们再使用len()方法去计算列表中的元素个数

2、抓取小猪短租网的列表页和详情页数据

1. 列表页的抓取

def item_link_list(page):
    for i in range(1,page+1):
        ti = random.randrange(1,4)
        time.sleep(ti)
        url = 'http://sh.xiaozhu.com/search-duanzufang-p{}-0/'.format(i)
        print(url)
        wb_data = requests.get(url)
        soup = BeautifulSoup(wb_data.text,'lxml')
        urls = imgs = soup.select('ul.pic_list.clearfix > li > a')
        prices = soup.select('div.result_btm_con.lodgeunitname > span > i')
        titles = soup.select('div.result_btm_con.lodgeunitname > div.result_intro > a > span')
        for title,url,price,img in zip(titles,urls,prices,imgs):
            da = {
                'title' : title.get_text(),
                'url' : url.get('href'),
                'price' : price.get_text(),
            }
            print(da)

结果为

1.jpg

2.根据url抓取详情页数据

def returnSex(sexclass):
    if sexclass == 'member_ico':
        return '男'
    if sexclass == 'member_ico1':
        return '女'

def item_detail(url):
    wd_data = requests.get(url)
    soup = BeautifulSoup(wd_data.text,'lxml')
    title = soup.select('div.pho_info > h4 > em')[0].get_text()
    address = soup.select('div.pho_info > p > span.pr5')[0].get_text()
    price = soup.select('div.day_l > span')[0].get_text()
    img = soup.select('#curBigImage')[0].get('src')
    host_img = soup.select('div.member_pic > a > img')[0].get('src')
    host_sex = soup.select('div.member_pic > div')[0].get('class')[0]
    host_name = soup.select('#floatRightBox > div.js_box.clearfix > div.w_240 > h6 > a')[0].get_text()
    data = {
        'title': title,
        'address': address.strip().lstrip().rstrip(','),
        'price': price,
        'img': img,
        'host_img': host_img,
        'ownersex': returnSex(host_sex),
        'ownername': host_name
    }
    print(data)

结果为#

1.jpg

3.总结

这次的作业基本无太大的问题,最难的是判断房东的性别,需要通过类名来判断

3.抓取Weheartit前20页数据

根据传入页数抓取1到页数的所有图片链接

def get_list_imgs(page):
    for index in range(1,page+1):
        time.sleep(3)
        url = 'http://weheartit.com/recent?scrolling=true&page={0}'.format(index)
        wb_data = requests.get(url)
        soup = BeautifulSoup(wb_data.text,'lxml')
        imgs = soup.select('img.entry_thumbnail')
        for img in imgs:
            img = img.get('src')
            down_url.append(img)
        print(url)

根据url下载图片

def down_img(urls):
    for item in urls:
        time.sleep(1)
        name = item[-24:-15]
        urlsd = path + name + '.jpg'
        print(urlsd)
        urllib.request.urlretrieve(item, urlsd)
        print('Done')

4.抓取58同城的列表页和详情页

首先是根据用户的类别和要抓取的页数来获得物品的链接地址

def get_item_list(who_sells,page):
    links = []
    for index in range(1,page+1):
        url = 'http://bj.58.com/pbdn/{}/pn{}'.format(str(who_sells),index)
        wb_data = requests.get(url)
        soup = BeautifulSoup(wb_data.text,'lxml')
        for item_url in soup.select('td.t > a.t'):
            if  'bj.58.com' in str(item_url):
                link = item_url.get('href').split('?')[0]
                links.append(link)
            else:
                pass
    return links

再根据链接地址抓取物品的信息

# 获得物品成色
def get_quality(qu):
    if qu == '-':
        return '不明'
    else:
        return qu

def get_detail_item(url):
    wb_data = requests.get(url)
    soup = BeautifulSoup(wb_data.text,'lxml')
    category = soup.select('div.breadCrumb.f12 > span:nth-of-type(3) > a')[0].get_text()
    title = soup.select('div.col_sub.mainTitle > h1')[0].get_text()
    date = soup.select('li.time')[0].get_text()
    price = soup.select('span.price.c_f50')[0].get_text()
    quality = soup.select('div.su_con > span')[1].get_text().strip().lstrip().rstrip(',')
    quality = get_quality(quality)
    area = list(soup.select('.c_25d')[0].stripped_strings) if soup.find_all('span','c_25d') else None
    date = {
        'category' : category,
        'title' : title,
        'date' : date,
        'price' : price,
        'quality' : quality,
        'area' : area
    }
    print(date)

通过这儿一周的练习,我了解了有关于爬虫的基本信息。也在课外爬了一些网页作为练习。深感python语言的精妙之处,希望在第二周的学习中更近一步

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容