【发布时间】: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