本文将介绍基于Python使用BeautifulSoup爬取微博热搜榜的实现过程
1、首先导入需要使用的库
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
2、打开网页,将饱满的网页做成美味的汤(滑稽)。
注意decode('utf-8')是为了解析并显示中文网站,features='lxml'是为了使用‘lxml’的格式进行解析。
url="https://s.weibo.com/top/summary?cate=realtimehot"
html=urlopen(url).read().decode('utf-8')
soup=BeautifulSoup(html,features='lxml')
3、重中之重——找规律
观察网页源代码,提取规律(即rank,name和number),我们以前三条为例子进行观察,可以发现rank信息都位于tr下td的class=''td-01 ranktop''中,name位于<a中的target=“_blank”中,而number位于'span'中。