【问题标题】:Is it possible to just get the tags without a class or id with BeautifulSoup?是否可以使用 BeautifulSoup 获取没有类或 id 的标签?
【发布时间】:2020-03-03 22:46:06
【问题描述】:

我有数千个 HTML 站点,我正在尝试从这些站点中过滤文本。

我正在用美味的汤做这个。 get_text() 为我提供了来自这些网站的许多不必要的信息。

因此我写了一个循环:

l = []
for line in text5:                   
    soup = bs(line, 'html.parser')
    p_text = ' '.join(p.text for p in soup.find_all('p'))  
    k = p_text.replace('\n', '')
    l.append(k)

但是这个循环给了我以<p开头的标签中的所有内容。

例如:

我想要两个普通的<p> 标签之间的所有内容。 但我也从这样的地方得到内容:

<p class="header-main__label"> bla ba </p>.

我可以告诉 BeautifulSoup 只获取普通的<p> 标签吗?

【问题讨论】:

  • soup.find_all('p', class_=False)

标签: python beautifulsoup


【解决方案1】:

你可以为classid设置False,它会得到没有classid的标签

soup.find_all('p', {'class': False, 'id': False})

或者(单词class__,因为Python中有关键字class

soup.find_all('p', class_=False, id=False)

from bs4 import BeautifulSoup as BS

text = '<p class="A">text A</p>  <p>text B</p>  <p id="C">text C</p>'

soup = BS(text, 'html.parser')

# ----

all_items = soup.find_all('p', {'class': False, 'id': False})

for item in all_items:
    print(item.text)

# ---

all_items = soup.find_all('p', class_=False, id=False)

for item in all_items:
    print(item.text)

编辑:如果你想要没有任何属性的标签,那么你可以使用not item.attrs过滤项目

for item in all_items:
    if not item.attrs:
        print(item.text)

from bs4 import BeautifulSoup as BS

text = '<p class="A">text A</p> <p>text B</p> <p id="C">text C</p> <p data="D">text D</p>'

soup = BS(text, 'html.parser')

all_items = soup.find_all('p')

for item in all_items:
    if not item.attrs:
        print(item.text)

【讨论】:

  • 谢谢,很好的回答!
猜你喜欢
  • 2020-02-05
  • 1970-01-01
  • 2015-08-29
  • 2019-03-25
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-15
相关资源
最近更新 更多