爬虫大作业

import requests
from bs4 import BeautifulSoup


def catchSoup(url):
    #url=‘http://www.18ladys.com/post/buchong/‘
    res=requests.get(url)
    res.encoding=‘utf-8‘
    soup=BeautifulSoup(res.text,‘html.parser‘)
    return soup

def kindSearch(soup):
    herbKind=[]
    for new in soup.select(‘li‘):
        if(new.text!=‘首页‘):
            perKind=[]
            perKind.append(new.text)
            perKind.append(new.select(‘a‘)[0].attrs[‘href‘])
            herbKind.append(perKind)
    return herbKind


def nameSearch(soup):
    herbName=[]
    for new in soup.select(‘h3‘):
        pername=new.text.split(‘_‘)[0].rstrip(‘图片‘).lstrip(‘\xa0‘)
        pername=pername.rstrip(‘的功效与作用‘)
        herbName.append(pername)
    return herbName

def perPage(soup):
    kindPage=[]
    add=[]
    for new in soup.select(‘.post.pagebar‘):
        for detail in new.select(‘a‘):
            d=[]
            d.append(detail.text)
            d.append(detail.attrs[‘href‘])
            kindPage.append(d)
    kindPage.remove(kindPage[0])
    kindPage.remove(kindPage[-1])
    return kindPage
def herbDetail(kind):
    soup=catchSoup(‘http://www.18ladys.com/post/buchong/‘)
    kindName=kindSearch(soup)[kind][0]       
    adds=kindSearch(soup)[kind][1]           
    totalRecord = []                        
    print("正在爬取 "+str(kind)+‘.‘+kindName)
    totalRecord.append(nameSearch(catchSoup(adds)))
    for add in perPage(catchSoup(adds)):           
        pageAdd=add[1]
        totalRecord.append(nameSearch(catchSoup(pageAdd)))
        #print(nameSearch(catchSoup(pageAdd)))
    print(totalRecord)
    return totalRecord


if __name__=="__main__":
       totalKind=kindSearch(catchSoup(‘http://www.18ladys.com/post/buchong/‘))     totalRecord=[]
    kind=0
    detailContent = ‘‘
    while(kind<20):
        totalRecord=herbDetail(kind)
        if(kind==0):
            detailContent+=‘目录:\n‘
            for i in totalKind:
                detailContent+=str(totalKind.index(i)+1)+‘.‘+i[0]+‘ ‘
            kind+=1
            continue
        else:
            detailContent+=‘\n‘+str(totalKind[kind][0])+‘:\n‘
        for i in totalRecord:
            detailContent+=str(totalRecord.index(i)+1)+‘.‘+i[0]+‘ ‘
        kind+=1

f = open(‘herbDetail.txt‘, ‘a+‘,encoding=‘utf-8‘)
f.write(detailContent)
f.close()


 




转载于:https://www.cnblogs.com/SOLARLKS/p/8970848.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值