【问题标题】:BeautifulSoup and Python Remove HTML TagsBeautifulSoup 和 Python 删除 HTML 标签
【发布时间】:2020-03-08 08:01:57
【问题描述】:

我需要帮助从我的脚本结果中解析出HTML 标记。我想将结果放在一个对象中以转换为 json。当我打印对象时,一切正常,除了我不能只提取没有 html 标记的文本。我一直在这个网站上搜索答案并尝试了各种方法来删除标签,但我不确定我做错了什么。感谢您的帮助。

根据我在这里阅读的一些内容,我尝试打印 teamObject.text 但这不起作用。

def make_soup(url):
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')
    return soup

soup = make_soup("team.html")
for record in soup.findAll('tr'):
    teamObject = {"name": record.find('a'),"description": record.find('p')}
    print (teamObject)

我希望在没有 html 标记的对象形式中看到结果。

按 cmets 更新:

我目前看到的只是打印我上面的代码的结果是:

{'name': <a href="/team/001"> Team 1 </a>, 'description': <p><a href="/team/001">Team 1</a> is a team does cool things.</p>}

更新代码以包含 .text:

def make_soup(url):
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')
    return soup


soup = make_soup("team.html")
for record in soup.findAll('tr'):
    teamObject = {
        "name": record.find('a').text,
        "description": record.find('p').text
        }
    print (teamObject)

我得到这个结果:

"name": record.find('a').text,
AttributeError: 'NoneType' object has no attribute 'text'

我希望只看到没有 html 标记的文本。

【问题讨论】:

  • 用当前和预期的结果更新帖子,让读者有一个清晰的想法。
  • 使用 soup.get_text() 怎么样,这应该只返回内容中的文本。
  • 根据建议更新

标签: python html web-scraping beautifulsoup tags


【解决方案1】:

尝试对循环中每条记录的查找结果使用.text。

for record in soup.findAll('tr'):
    teamObject = {
        "name": record.find('a').text,
        "description": record.find('p').text
        }

.text 调用.get_text(),所以这与上面的评论类似,但我认为您希望在最后一次搜索中获得文本结果。

如果您需要传入参数进行格式化,您可以使用 get_text()。 See the docs

编辑:

收到 NoneType 错误告诉我您有一些 &lt;tr&gt; 标签不包含 &lt;a&gt; 或 &lt;p&gt; 标签。如果record.find在循环中找不到结果,则返回None,不能返回文本值。

您可以通过逻辑解决此问题,或者重新评估您的搜索方式。 hacky 方法是在返回文本之前检查您是否有所需的标签。

for record in soup.findAll('tr'):
    if record.a and record.p:
        teamObject = {
            "name": record.find('a').text,
            "description": record.find('p').text
            }

这可确保您不会收到 None 错误,但现在您将完全跳过任何缺少 &lt;a&gt; 或 &lt;p&gt; 标记的行,所以要小心。

如果您确信相关行将始终包含 &lt;a&gt; 和 &lt;p&gt; 标签,则可以通过仅返回包含“团队”的行来集中搜索以排除任何错误的 &lt;tr&gt; 条目。

for record in soup.select('tr:contains("Team")'):
    teamObject = {
        "name": record.find('a').text,
        "description": record.find('p').text
        }

【讨论】:

  • 感谢您的回复。我用更多信息更新了我的帖子。我实际上尝试过这个..也许我错过了什么?谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
相关资源
最近更新 更多