处理HTML页面,经常使用的便是使用beautifulsoup库
pip install beautifulsoup4
执行上述语句下载bs4库
一般请求下来的所需数据都位于tbody的tr标签里,下面给出对应代码:
soup = BeautifulSoup(r.text, "html.parser")
informationlist=[]for tr in soup.find('tbody').children:#出现/n情况,/n在soup中被认为是子节点之一
if(tr!='\n'):
tds= tr('td')
informationlist.append([tds[0].string, tds[1].string, tds[8].string])for i inrange(len(informationlist)):
information=informationlist[i]print("{:^10}\t{:^6}\t{:^10}".format(information[0], information[1], information[2]))
Tag:标签,最基本的信息组织单元,分别用<>和>标明开头和结尾
Name:标签的名字,
…
的名字是'p',格式:.nameAttributes:标签的属性,字典形式组织,格式:.attrs
NavigableString:标签内非属性字符串,<>…>中字符串,格式:.string
Comment:标签内字符串的注释部分,一种特殊的Comment类型
遍历方法:
for child insoup.body.children:print(child)for child insoup.body.descendants:print(child)
下面给出一些常用的属性
.contents:子节点的列表,将所有儿子节点存入列表
.children:子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
.descendants:子孙节点的迭代类型,包含所有子孙节点,用于循环遍历
.parent:节点的父亲标签
.parents:节点先辈标签的迭代类型,用于循环遍历先辈节点
.next_sibling:返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling:返回按照HTML文本顺序的上一个平行节点标签
.next_siblings:迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings:迭代类型,返回按照HTML文本顺序的前续所有平行节点标签