【问题标题】:How can i make BeautifulSoup finde more than one tag?我怎样才能让 BeautifulSoup 找到多个标签?
【发布时间】:2020-06-10 23:00:49
【问题描述】:

我正在测试一个程序,用于将维基百科的内容打印到提示中。我已经得到了一些输出,但它有点乱。所以我想只获取标签<p><b> 的内容,这两个标签是维基百科用来显示内容的。这是我的代码:

import urllib.request
from bs4 import BeautifulSoup


URL = input("Enter the url (only wikipedia supported, default url https://?.wikipedia.org/wiki) :  ")



page = urllib.request.urlopen(URL)
html_doc = page.read()
soup = BeautifulSoup(html_doc, 'html.parser')





for x in soup.find_all('p').find_all('b'):
    print(x.string)

询问标记是因为维基百科在那里显示了语言,所以它取决于。如您所见,我又添加了一个 .find_all ,因为我不知道如何添加它。对不起我的英语不好和我的代码不好,因为我与这个请求字段不太相关。谢谢

【问题讨论】:

  • 那么你想搜索<p>标签下的所有<b>标签吗?或者对于所有<b> 标签和<p> 标签?
  • 用于 b 和 p 标签
  • 你应该得到一个错误,因为find_all 不是ResultSet 的方法。您能否发布回溯,以便人们了解问题所在?

标签: python python-3.x


【解决方案1】:

BeautifulSoup.find_all 返回一个ResultSet,它本质上是一个元素列表。您需要自己遍历该列表以进行第二次操作。

import urllib.request
from bs4 import BeautifulSoup

URL = input("Enter the url (only wikipedia supported, default url https://?.wikipedia.org/wiki) :  ")

page = urllib.request.urlopen(URL)
html_doc = page.read()
soup = BeautifulSoup(html_doc, 'html.parser')

for elem in soup.find_all('p'):
    for x in elem.find_all('b'):
        print(x.string)

【讨论】:

  • 使用该代码,我只得到 标记内的单词,而 标记又位于

    标记内。我需要的是

    标签内的单词以及

    标签内的 标签。一直感谢你帮助我

  • “也”是什么意思?是否要忽略 <b> 以外的标签内容,如果它们恰好出现在 <p> 中?
猜你喜欢
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
相关资源
最近更新 更多