Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 漂亮的汤循环元素,只有在存在任何元素及其父元素时才能获取当前元素的文本_Python_Python 3.x_Beautifulsoup_Lxml - Fatal编程技术网

Python 漂亮的汤循环元素,只有在存在任何元素及其父元素时才能获取当前元素的文本

Python 漂亮的汤循环元素,只有在存在任何元素及其父元素时才能获取当前元素的文本,python,python-3.x,beautifulsoup,lxml,Python,Python 3.x,Beautifulsoup,Lxml,我正在学习BeautifulSoup,有一个网页,有一个类似这样的主体: html: 我能够得到结果,但问题是在div中,我也得到了锚文本,如下所示 div this is div text this is anchor text div.table.tr.td a this is anchor text div.table.tr.td.a 下面是我的代码 f = open("C:/abc.html",encodin

我正在学习BeautifulSoup,有一个网页,有一个类似这样的主体:

html:

我能够得到结果,但问题是在div中,我也得到了锚文本,如下所示

div       this is div text this is anchor text     div.table.tr.td
a         this is anchor text                      div.table.tr.td.a
下面是我的代码

f = open("C:/abc.html",encoding="utf8")  
soup=BeautifulSoup(f,"lxml")
f.close()
for tag in soup.find_all():
      allparent=""
      for parenttags in tag.findParents():
          allparent=parenttags.name+"."+allparent
      if allparent!="":
          allparent=allparent[:-1]
      print(tag.name+"', '"+tag.text+"','"+allparent)

您正在查找标签。查找(text=True)

如果
tag
是您的
foobar

  • tag.find(text=True)
    将输出
    foo
  • tag.text
    将输出
    foo-bar
因此,在你的情况下,只需更换

print(tag.name+"', '"+tag.text+"','"+allparent)`


或者更好

print('"{}", "{}", "{}"'.format(tag.name, tag.find(text=True), allparent))

那不是更性感吗

你到底想做什么?@PadraicCunningham我想用它自己的文本和所有父标记来获取所有标记。此外,我将根据父母的数据分组,以获得相同类型标记和其他计算中的平均字数。
print(tag.name+"', '"+tag.text+"','"+allparent)`
print(tag.name+"', '"+tag.find(text=True)+"','"+allparent)
print('"{}", "{}", "{}"'.format(tag.name, tag.find(text=True), allparent))