python定向爬虫实例(三)

功能:爬取百度热搜的实时排行榜信息

程序设计:

  • 爬取百度热搜网页的HTML文本
  • 解析HTML文本获取排名、热度信息
  • 将获取到的信息以字典的形式存储到文件中

代码:

#爬取百度热搜的实时排行榜
#技术路线:requests---bs4
import requests
from bs4 import BeautifulSoup

def getHTML(url):
    try:
        r=requests.get(url,headers={'User-Agent':'Mozilla/5.0'})
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        return ""

def parseHTML(demo,file_path):
    f=open(file_path,"w")
    soup=BeautifulSoup(demo,"html.parser")
    num_list=soup.find_all('td','first')
    title_list=soup.find_all('a','list-title')
    for i in range(len(num_list)):
        info_dict={}
        try:
            info_dict.update({
                '排名':num_list[i].find('span').string,
                '标题':title_list[i].string,
            })
            f.write(str(info_dict)+'\n')
        except:
            continue
    f.close()
    print("爬取完毕!")
def main():
    url='http://top.baidu.com/buzz?b=1&fr=20811'
    file_path="D://百度实时热搜排行.txt"
    demo=getHTML(url)
    parseHTML(demo,file_path)

main()

结果:

 

转载于:https://www.cnblogs.com/BUPT-MrWu/p/11349130.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值