BeautifulSoup4中find 和find_all分别有不同的含义,find返回的是TAG对象,只有一个值,可以直接使用属性例如,children。而find_all返回的是TAG对象的迭代对象,不能直接用TAG的属性,但是里面每个元素是TAG,可以用属性
import requests
from bs4 import BeautifulSoup
import bs4;
mytext=requests.get("http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html")
mytext.encoding="utf-8"
mysoup=BeautifulSoup(mytext.text)
t1=mysoup.find("td")
t2=mysoup.find_all("td")
print(type(t1))
print(type(t2))
#find返回的是TAG对象,只有一个值,可以直接使用属性例如,children
#而find_all返回的是TAG对象的迭代对象,不能直接用TAG的属性,但是里面每个元素是TAG,可以用属性
print(t1)
print(len(t2))
# t2=mysoup.find_all("td")
# for i in t2:
# print(i.string)
# for i in t1:
# if isinstance(i,bs4.element.Tag):
# x=i.find_all("td")
# print(len(x),end=" ")
# print(x[0].string,x[1].string,x[2].string,x[3].string,x[4].string)
17686
例题:查询大学排名的四种方法
import requests
from bs4 import BeautifulSoup
import bs4;
mytext=requests.get("http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html")
mytext.encoding="utf-8"
mysoup=BeautifulSoup(mytext.text)
#find返回的是TAG对象,只有一个值,可以直接使用属性例如,children
#而find_all返回的是TAG对象的迭代对象,不能直接用TAG的属性,但是里面每个元素是TAG,可以用属性
#方法一:find
print("---111"*30)
t1=mysoup.find("tbody").children
print(type(t1))
for i in t1:
if isinstance(i,bs4.element.Tag): #列表中TAG对象,有非TAG对象,是大量的空格
x=i.find_all("td") #表格中的一行
print(len(x),end=" ") #列表里面元素个数
print(x[0].string,x[1].string,x[2].string,x[3].string,x[4].string)
#方法二:find_all---1
print("---222"*30)
t2=mysoup.find_all("tbody")
print('mysoup.find_all("tbody")',type(t2),len(t2))
tt=t2[0] #取列表里面的第一个元素,是TAG,
print('mysoup.find_all("tbody")[0]',type(tt),len(tt))
for i in tt:
if isinstance(i, bs4.element.Tag): # 列表中TAG对象,有非TAG对象,是大量的空格
x = i.find_all("td") # 表格中的一行
print(len(x), end=" ") # 列表里面元素个数
print(x[0].string, x[1].string, x[2].string, x[3].string, x[4].string)
#方法三:find_all---2
print("---333"*30)
t2=mysoup.find_all("tbody")#网页的取表格
print('mysoup.find_all("tbody")',type(t2),len(t2))
tt=t2[0] #取列表里面的第一个元素,是TAG,取第一个表格
print('mysoup.find_all("tbody")[0]',type(tt),len(tt))
tt1=tt.find_all("tr")#取表格里面的所有行
for i in tt1:
j=i.find_all("td")#每行里面的素有列
for x in j:
print(x.string,end=" ")#每列数据输出
print()
#方法四:find,find_all
print("---444"*30)
t1=mysoup.find("tbody")#网页的第一个取表格
tt1=t1.find_all("tr")#取表格里面的所有行
for i in tt1:
j=i.find_all("td")#每行里面的素有列
for x in j:
print(x.string,end=" ")#每列数据输出
print()
print("-444-over"*10)