python:查找html标签并替换它们的属性 [英] python: find html tags and replace their attributes

查看:276
本文介绍了python:查找html标签并替换它们的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行以下操作:

  1. 获取html文档
  2. 找到所有出现的 'img' 标签
  3. 获取他们的 'src' 属性
  4. 将建立的 url 传递给处理
  5. 将 'src' 属性更改为新的
  6. 使用 Python 2.7 完成所有这些工作

附言我听说过 lmxl 和 BeautifulSoup.你建议如何解决这个问题?也许使用正则表达式会更好?还是别的什么?

P.S. I,ve heard about lmxl and BeautifulSoup. How do you recommend to solve this problem with? Maybe it would be better to use regexes then? or another something else?

推荐答案

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_string)
for link in soup.findAll('a')
    link['src'] = 'New src'
html_string = str(soup)

我不是特别喜欢 BeautifulSoup,但它可以为您完成工作.如果没有必要,尽量不要过度执行您的解决方案,这是解决一般问题时可以做的更简单的事情之一.

I don't particularly like BeautifulSoup but it does the job for you. Try to not over-do your solution if you don't have to, this being one of the simpler things you can do to solve a general issue.

也就是说,为未来而构建同样重要,但您可以将所有 6 个要求合而为一,我想将 'src' 或所有链接更改为 X"

That said, building for the future is equally important but all your 6 requirements can be put down into one, "I want to change 'src' or all links to X"

这篇关于python:查找html标签并替换它们的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆