BeautifulSoup技术爬取豆瓣TOP250

爬取豆瓣top250

1.环境:VS2019
2.首先安装re, BeautifulSoup,codecs,requests库,可以用 pip安装
功能:将top250的电影名,评分,评价人数,链接,影评获取下来并生成.html文件 效果如图:

截图
先展示爬虫函数:

def pachong(url):
   cc = requests.get(url,headers=headers)
   cc=cc.text
   cc = BeautifulSoup(cc,"html.parser")
   print(u'豆瓣top250 \n')
   for tag in cc.find_all(attrs={"class":"item"}):
       shu = tag.find('em').get_text() #序号
       print (shu)
       outf.write(u"<tr><th>"+ shu)

       name = tag.find_all(attrs={"class":"title"}) #中文名称
       zname = name[0].get_text()
       print (u'[名称]',zname)
       outf.write(u"</th><th>"+ zname)

       urlm = tag.find(attrs={"class":"hd"}).a  #链接
       urls = urlm.attrs['href']
       print (u'[链接]',urls)
       outf.write(u"</th><th>"+urls)

       ping = tag.find(attrs={"class":"star"}).get_text() #评分评论
       ping = ping.replace('\n',' ')
       ping = ping.lstrip()
       mode = re.compile(r'\d+\.?\d*')
       mm = mode.findall(ping)
       k=0
       for n in mm:
           if k==0:
               print (u"[分数]"+n)
               outf.write(u"</th><th>" + n)
           elif k==1:
               print (u"[评论人数]"+n)
               outf.write(u"</th><th>" +n)
           k=k+1
       
       yu = tag.find(attrs={"class":"inq"}) #评语
       if(yu):
           content = yu.get_text()
           print (u'[评语]',content)
           outf.write(u"</th><th>")
           outf.write(content)
           outf.write(u"</th></tr>"+"\n")

注意:1.爬取豆瓣网时需要有请求头
2.此处用的beautifsoup技术进行爬取
3.写入的文件的是.html所以有<th></th><tr>等写入文件,这是.html语言

因为一个网页只有部分电影所以需要翻页爬取,顾在主函数时要多次调用pachong函数
完整代码见下一篇博客。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

好人嬴政

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值