前置条件:安装python,库:requests,lxml,beautifulsoup。
sublimetext的插件(自动填充)可选。
1,html相关。
与第一节的最简单html页面相比,多了评分和分类。
注意观察源代码,是用两个div表示的。其中:
使用 <span> 元素对文本中的一部分进行着色:
<p>我的母亲有 <span style="color:blue">蓝色</span> 的眼睛。</p>
2,在新建的py文件里,首行书写:from bs4 import BeautifulSoup
其中,bs4是模块名称
3,因为是对本地文件进行解析,所以采用打开本地文件的方式。
with open('C:/Users/Keiven/Desktop/python/课程源码及作业参考答案bak/Plan-for-combating-master/week1/1_2/1_2code_of_video/web/new_index.html','r') as f:
with open() as xx:,其中的地址可以是绝对地址(全部路径,但注意反斜杠的不同),也可以是相对路径(python文件和待解析的文件放一起)。
4,soup=BeautifulSoup(f,'lxml')
解析文件到soup对象里。print(soup)后会发现就是大量的源代码,此后的过程就是对立面的内容进行提取(select)
5,路径
想对大量繁杂的代码提取,就要找到待提取对象的路径(path)




beautifulsoup只认可css selector路径。
images=soup.select('路径') #对soup对象使用select方法,参数使用路径。
直接拷贝的路径:body > div.main-content > ul > li:nth-child(1) > img
直接填写到上方select方法后,print后发现只能找到一个图片,是因为这就是具体某个图片的地址,改造:
body > div.main-content > ul > li > img
同理,可以构造titles,descs,rates,cates

上图的print方法里使用了sep参数来实现多个参数的格式化,sep表示多个参数之间用换行符和横线隔开。
6,对标签里的文本进行筛选。

(1)举例,针对titles=soup.select()

使用for循环,利用get_text方法逐个提取title

(2)目的是得到规整的数据,如下图。因此使用字典的方式构造数据结构

使用元素构造字典数据结构,就要逐个依次的读取出来。因此首先用for循环结合zip一次性读取。

不同于其他的描述,image的链接地址是img标签的属性,使用get函数(属性名称)的方式读取。

发现bug:分类只显示了一个,而有的文章属于两个或多个分类,什么原因呢?

而观察html源代码发现,span是具体到了每一个分类下,因此针对这种有父节点,我们需要多个子节点的情况,拷贝地址的时候就需要删掉子节点。


那么现在因此存在多个子节点,就不能直接get_text(),需要使用一个特殊的方法。
cate.stripped_strings来表示获取到的多个子节点,以列表的方式表示出来,就需要前面list()一下。


上面的结果这么列出来不方便查询和读取(独立的),用一个列表,把他们装起来。
Info=[]
在构造字典的时候就把data装到info里。然后逐一读取和查询。

网友评论