人生不能放弃,就算是停电
很不幸,公司停电,刚刚打的代码全没有了
但还是要面对现实
加油!!!,不以物喜不以己悲
今天的学习目标是:beautifulsoup中使用css语法元素
使用css语法查找元素,需要使用css语法规则
使用方法
tag.select(css)
其返回值为一个列表,即使只有一个值
tag是一个bs4.element.Tag对象,即HTML中的一个element节点元素,select是查找方法
css是类似于css语法的一个字符串
soup.select(‘a’)查找文档中所有的元素节点
soup.select(‘p[class=‘story’] a’)查找文档中所有属性有class为story的
节点下面的所有元素的节点
soup.select(‘p[class] a’)查找文档中所有具有class属性的
节点下的所有元素节点
soup.select(‘a[id=‘link1’]’)查找文档中属性id为link1的节点
soup.select(‘body head title’)查找文档中body下面的head下面的title节点
soup.select(‘body[class]’)查找文档中body下面所有具有class属性的节点
soup.select(‘body[class] a’)查找文档中body下面所有具有class属性的节点下面的节点
需要注意的是其中的语法规则:
元素后面的[]为紧挨着元素属性,但是下一级的属性就需要空格间隔,不然调试的时候会经常出错
from bs4 import BeautifulSoup
# find_all or find
doc = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Dormouse's story</title>
</head>
<body>
<p class="title"><b>The Dormouse's story<i>the</i></b></p>
<p class="story">
Once upon a time there were three little sister;and their names were
<a href="http://example.com/else" class="sister" id="link1">Elsie</a>
<a href="http://example.com/