【问题标题】:Using BeautifulSoup's replaceWith to replace all 'a' tags with tag content使用 BeautifulSoup 的 replaceWith 将所有 'a' 标签替换为标签内容
【发布时间】:2013-03-11 21:47:29
【问题描述】:

编辑:基本上,我正在尝试执行分解,但不是删除标签并完全破坏其内容,而是将标签替换为其内容。

我想用字符串格式的标签内容替换 html 文档中的所有“a”标签。这将使我能够更轻松地将 html 写入 csv。但是,我无法通过替换步骤。我一直在尝试使用 BeautifulSoup 的 replace_with() 来完成它,但结果并没有按预期返回。

# Import modules
from bs4 import BeautifulSoup
from urllib2 import urlopen

# URL to soup
URL = 'http://www.barringtonhills-il.gov/foia/ordinances_12.htm'
html_content = urlopen(URL).read()
soup = BeautifulSoup(html_content)

# Replaces links with link text
links = soup.find_all('a')
for link in links:
    linkText = link.contents[0]
    linkTextCln = '%s' % (linkText.string)
    if linkTextCln != 'None':
        link.replaceWith(linkTextCln)
        print link

这会返回:

<a href="index.htm">Home</a>
<a href="instruct.htm">Instructions</a>
<a href="requests.htm">FOIA Requests</a>
<a href="kiosk.htm">FOIA Kiosk</a>
<a href="geninfo.htm">Government Profile</a>
etc etc etc

但预期回报是:

Home
Instructions
FOIA Requests
FOIA Kiosk
Government Profile
etc etc etc

关于为什么 replaceWith 没有按预期工作的任何想法?有没有更好的方法来解决这个问题?

【问题讨论】:

  • 您的结果中仍然会出现非字符串 HTML 内容。返回:[] [u'Home'] [u'Instructions'] [u'FOIA Requests'] 等等...等等...
  • link.contents 与 linkTextCln 不是我的问题——尝试用 link.contents 替换链接标签也不起作用。
  • 基本上,我正在尝试执行分解,但不是删除标签并完全破坏其内容,我想用它的内容替换标签/

标签: python html-parsing beautifulsoup


【解决方案1】:

我相信使用 bs4,该方法现在是 replace_with 但如果您只是想输出标签的内容,则可以使用以下方法:

from bs4 import BeautifulSoup

s = '''
<a href="index.htm">Home</a>
<a href="instruct.htm">Instructions</a>
<a href="requests.htm">FOIA Requests</a>
<a href="kiosk.htm">FOIA Kiosk</a>
<a href="geninfo.htm">Government Profile</a>
'''
soup = BeautifulSoup(s, 'html.parser')

for tag in soup.findAll('a'):
    print(tag.string)

输出:

Home
Instructions
FOIA Requests
FOIA Kiosk
Government Profile
[Finished in 0.2s]

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 2014-03-09
    • 2014-06-19
    • 1970-01-01
    • 2021-08-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    相关资源
    最近更新 更多