【问题标题】:Remove img tags from xml with BeautifulSoup使用 BeautifulSoup 从 xml 中删除 img 标签
【发布时间】:2019-05-11 23:20:29
【问题描述】:

这是我第一次使用 Python 和 BeautifulSoup。问题是我正在将博客中的所有文章从一个网站迁移到另一个网站,为了执行此操作,我从 xml 文件中提取某些信息;我的代码的最后一部分告诉我们只从元标记中提取位置 0 和 164 之间的文本,这样它就可以在谷歌 SERP 上按照他们想要的方式出现。

这里的问题是博客中的一些文章在标签内的第一行有 img 标签,我想删除它们,包括 src 属性,这样代码就可以只抓取这些 img 标签之后的文本。

我尝试了很多方法来解决它,但我没有成功。

这是我的代码:

from bs4 import BeautifulSoup
from urllib2 import urlopen
import csv
import sys
import re

reload(sys)
sys.setdefaultencoding('utf8')

base_url = ("http://pimacleanpro.com/blog?rss=true")
soup = BeautifulSoup(urlopen(base_url).read(),"xml")

titles = soup("title")
slugs = soup("link")
bodies = soup("description")

with open("blog-data.csv", "w") as f:
    fieldnames = ("title", "content", "slug", "seo_title", "seo_description","site_id", "page_path", "category")
    output = csv.writer(f, delimiter=",")
    output.writerow(fieldnames)

    for i in xrange(len(titles)):
        output.writerow([titles[i].encode_contents(),bodies[i].encode_contents(formatter=None),slugs[i].get_text(),titles[i].encode_contents(),bodies[i].encode_contents(formatter=None)[4:164]])

print "Done writing file"

任何帮助将不胜感激。

【问题讨论】:

  • 是的,但我不知道如何将其融入语法。这是我用python编写的第一个代码,我不知道如何完全解决它。你能帮帮我吗?
  • 你能更清楚你需要做什么吗?您想删除<img> 中的所有<img> 标记及其内容吗?此外,您似乎使用的是 Python 2。如果您只需要 Python 2 解决方案,则应标记 Python 2。
  • 谢谢@MihaiChelaru,我刚刚标记了Python 2。正如您在pimacleanpro.com/blog?rss=true 中看到的那样,有16 个 标签,其中一些在它之后有一个 标签,我需要省略/删除 img 标签,因此代码行 bodies[i].encode_contents(formatter=None)[4:164] 仅在第一个 img 之后从位置 4 到 164 获取文本标签。例如,您可以查看第三个 标签,它后面有一个 img 标签。

标签: python-2.7 beautifulsoup


【解决方案1】:

这是一个 Python 2.7 示例,我认为它可以满足您的需求:

from bs4 import BeautifulSoup
from urllib2 import urlopen
from xml.sax.saxutils import unescape

base_url = ("http://pimacleanpro.com/blog?rss=true")

# Unescape to allow BS to parse the <img> tags
soup = BeautifulSoup(unescape(urlopen(base_url).read()))

titles = soup("title")
slugs = soup("link")
bodies = soup("description")

print bodies[2].encode_contents(formatter=None)[4:164]

# Remove all 'img' tags in all the 'description' tags in bodies
for body in bodies:
  for img in body("img"):
    img.decompose()

print bodies[2].encode_contents(formatter=None)[4:164]

# Proceed to writing to CSV, etc.

第一个打印语句输出以下内容:

<img src='"http://ekblog.s3.amazonaws.com/contentp/wp-content/uploads/2018/09/03082910/decoration-design-detail-691710-300x221.jpg"'><br>
<em>Whether you are up

而去掉&lt;img&gt;标签后的第二个如下:

<em>Whether you are upgrading just one room or giving your home a complete renovation, it’s likely that your first thought is to choose carpet for all of

当然,如果您不感兴趣,您可以在创建 titles、slugs 或 bodies 之前删除汤对象中的所有图像标签:

for tag in soup("img"):
    tag.decompose()

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2017-03-31
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2011-04-04
    • 2020-10-27
    相关资源
    最近更新 更多