在python的bs4中将参数传递给findAll
我需要在函数中使用bs4的帮助。如果我想通过函数传递findAll(或find)的路径,它就不起作用。请看下面的样品在python的bs4中将参数传递给findAll,python,function,beautifulsoup,Python,Function,Beautifulsoup,我需要在函数中使用bs4的帮助。如果我想通过函数传递findAll(或find)的路径,它就不起作用。请看下面的样品 from bs4 import BeautifulSoup data = '<h1 class="headline">Willkommen!</h1>' def check_text(path, value): soup = BeautifulSoup(''.join(data), "lxml") x1 = "h1", {"clas
from bs4 import BeautifulSoup
data = '<h1 class="headline">Willkommen!</h1>'
def check_text(path, value):
soup = BeautifulSoup(''.join(data), "lxml")
x1 = "h1", {"class":"headline"}
x2 = path
x3 = tuple(path)
print type(x1), 'soup.findAll(x1)===', soup.findAll(x1)
print type(x2), 'soup.findAll(x2)===', soup.findAll(x2)
print type(x3), 'soup.findAll(x3)===', soup.findAll(x3)
for i in soup.findAll(x1):
print 'x1, text=', i.getText()
for i in soup.findAll(x2):
print 'x2, text=', i.getText()
for i in soup.findAll(x3):
print 'x3, text=', i.getText()
check_text('"h1", {"class": "headline"}', 'Willkommen!')
从bs4导入美化组
数据='Willkommen!'
def check_文本(路径、值):
soup=beautifulsou(“”.join(数据),“lxml”)
x1=“h1”,{“类”:“标题”}
x2=路径
x3=元组(路径)
打印类型(x1),“soup.findAll(x1)==”,soup.findAll(x1)
打印类型(x2),“soup.findAll(x2)==”,soup.findAll(x2)
打印类型(x3),“soup.findAll(x3)==”,soup.findAll(x3)
对于汤中的i.findAll(x1):
打印“x1,text=”,i.getText()
对于汤中的i.findAll(x2):
打印“x2,text=”,i.getText()
对于汤中的i.findAll(x3):
打印“x3,text=”,i.getText()
检查文本('h1',{class:'headline'}','Willkommen!')
输出是
<type 'tuple'> soup.findAll(x1)=== [<h1 class="headline">Willkommen! </h1>]
<type 'str'> soup.findAll(x2)=== []
<type 'tuple'> soup.findAll(x3)=== []
x1, text= Willkommen!
soup.findAll(x1)==[Willkommen!]
汤.芬德尔(x2)=[]
汤.芬德尔(x3)=[]
x1,text=Willkommen!
有人有解决办法吗?
感谢来自bs4 import BeautifulSoup的
数据='Willkommen!'
def check_文本(路径、值):
soup=beautifulsou(“”.join(数据),“lxml”)
x1=“h1”,{“类”:“标题”}
打印(类型(x1),“soup.findAll(x1)==”,soup.findAll(x1))
打印(类型(路径),“soup.findAll(路径)==”,soup.findAll(**路径))
对于汤中的i.findAll(x1):
打印('x1,text=',i.getText())
对于汤中的i.findAll(**路径):
print('path,text=',i.getText())
检查文本({'name':'h1','attrs':{'class:'headline'}},'Willkommen!')
传递字典,而不是作为字符串传递,字典的元素可以作为关键字参数传递给被调用函数 findAll方法将标记名作为第一个参数,而不是路径。 它返回名称与传递的标记匹配的所有标记,这些标记是调用它的标记的后代。 这是使用它的唯一方式(它不是用来接收路径的)。 查看更多详细信息 现在,
soup.findAll(path)
将查找名为path
的标记。
由于path=''h1',{“class”:“headline”}
,soup.findAll(path)
将在HTML字符串中查找
标记,而这些标记很可能不存在
所以,基本上,没有“路径”这样的东西。
不过,您使用的语法让我觉得您想要的标签的class
属性等于“headline”
。
为findAll
方法指定属性的方法是将它们作为字典传递给attrs
参数。
您可能想做的是:
soup.findAll('h1', attrs={'class': "headline"}, text="wilkommen")
soup.findAll('h1', attrs={'class': "headline"}, text="wilkommen")