【问题标题】:How to get rid of tags before and after?如何去除前后标签?
【发布时间】:2016-12-30 02:13:55
【问题描述】:

我当前的代码如下:

import requests
from bs4 import BeautifulSoup
url = "http://boost-heaven.com/sitemap_products_1.xml"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
urls = soup.find_all("url")
links = soup.find_all("loc")
title = soup.find_all("image:title")
time = soup.find_all("lastmod")
image = soup.find_all("image:loc")
i = 0
while i <= len(urls) - 1:
    for item in urls:
        if "products" in str(item):
            if "products" in str(links):
                print title[i - 1]
                print links[i]
                print time[i - 1]
                print image[i -1]
        i = i + 1

返回:

<image:title>PIN SWG</image:title>
<loc>http://boost-heaven.com/products/swg-pin</loc>
<lastmod>2016-12-29T06:13:25Z</lastmod>
<image:loc>https://cdn.shopify.com/s/files/1/1490/9704/products/swgpin2.jpgv=1479148164</image:loc>
<image:title>BEANIE</image:title>
<loc>http://boost-heaven.com/products/bg-beanie</loc>
<lastmod>2016-12-29T00:10:45Z</lastmod>
<image:loc>https://cdn.shopify.com/s/files/1/1490/9704/products/redswg.jpgv=1482967350</image:loc>
<image:title>BG FLOORMAT</image:title>
<loc>http://boost-heaven.com/products/bg-floormat</loc>
<lastmod>2016-12-29T09:47:00Z</lastmod>
<image:loc>https://cdn.shopify.com/s/files/1/1490/9704/products/floormatbg1.jpg?v=1482967260</image:loc>
<image:title>BG PABLO BURG</image:title>
<loc>http://boost-heaven.com/products/copy-of-bg-pablo-bn-t</loc>
<lastmod>2016-12-29T09:47:00Z</lastmod>
<image:loc>https://cdn.shopify.com/s/files/1/1490/9704/products/burgundypabloe.jpg?v=1482878401</image:loc>

我想去掉 loc、lastmod 和其他标签,只将文本留在其中,但我不知道该怎么做。我还想在 lastmod 的时间内删除“Z”并将“T”替换为“at”。谢谢。

【问题讨论】:

  • 使用image.get_text()image.text 而不是str(image),您不必删除标签。
  • 你在每个内部循环中循环相同的元素。 links = soup.find_all("lastmod") 每次都会得到相同的 lastmod 元素列表。
  • 顺便说一句,您在所有级别都使用相同的变量links,这非常令人困惑。
  • 为什么要使用html.parser 处理 XML?
  • 不要修改有问题的代码!您可以附加新代码,但始终保留原始问题和代码。

标签: python python-2.7 beautifulsoup python-requests


【解决方案1】:

我只在每个标签内获取所有&lt;url&gt; 标签和搜索元素。

import requests
from bs4 import BeautifulSoup

url = "http://boost-heaven.com/sitemap_products_1.xml"

r = requests.get(url)

soup = BeautifulSoup(r.content, "html.parser")

# skip first element which has no data
all_urls = soup.find_all("url")[1:]

for url in all_urls:
    print('image:title:', url.find('image:title').get_text())
    print('        loc:', url.find('loc').get_text())
    # skip last char - "Z"
    print('    lastmod:', url.find('lastmod').get_text().replace("T", " at ")[:-1])
    print('  image:loc:', url.find('image:loc').get_text())
    print('---')

你也可以不用find()这两条线

print('        loc:', url.loc.get_text())
print('    lastmod:', url.lastmod.get_text().replace("T", " at ")[:-1])

您也可以使用text 而不是get_text() - 即。 url.find('image:title').text

【讨论】:

    【解决方案2】:

    尝试在每个变量进入循环之前重新初始化它们,因为在循环中它很可能会获取第一个变量并将其循环到应该传递到循环中的每个其他项中。

    【讨论】:

      【解决方案3】:

      您的内部循环每次都遍历所有相同的元素,而不是与外部循环中的当前图像链接相关的元素。变量的最终值来自每个列表的最后一个元素,因此每次都得到相同的值。

      您应该循环遍历 &lt;url&gt; 元素,然后在其中找到特定项目。

      import requests
      from bs4 import BeautifulSoup
      
      url = "http://boost-heaven.com/sitemap_products_1.xml"
      r = requests.get(url)
      soup = BeautifulSoup(r.content)
      
      for url in soup.find_all("url"):
          titlenode = url.find("image:title")
          if titlenode:
              title = titlenode.text
              loc = url.find("loc").text
              lastmod = url.find("lastmod").text
              imageloc = url.find("image:loc").text
              print title + "\n" + loc + "\n" + lastmod + "\n" + imageloc
      

      【讨论】:

      • title = url.find("image:title").text AttributeError: 'NoneType' object has no attribute 'text'
      • 我得到同样的错误。
      • 我对其进行了测试,发现“xml”解析器会引发问题。 'lxml' 解析器工作正常。
      • 你必须先跳过没有数据的&lt;url&gt;
      • 我添加了一个检查以查看&lt;url&gt; 是否包含&lt;image:title&gt; 节点。然后它假定它将拥有所有其他节点。一个更安全的程序会在尝试获取其文本之前检查每个节点。
      猜你喜欢
      • 2019-06-02
      • 2017-09-21
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      相关资源
      最近更新 更多