【问题标题】:how do I create a list from a sitemap.xml file to extract the url in python?如何从 sitemap.xml 文件创建列表以在 python 中提取 url?
【发布时间】:2017-06-06 11:16:23
【问题描述】:

我需要创建一个代码来从一张图片中提取一个单词。 我将解释,从页面 sitemap.xml 中,我的代码必须尝试在此 xml 文件中存在的每个链接中,如果在图像链接中存在特定单词,则在每个链接中找到。

站点地图是 adidas = http://www.adidas.it/on/demandware.static/-/Sites-adidas-IT-Library/it_IT/v/sitemap/product/adidas-IT-it-it-product.xml

这是我为搜索图像创建的代码,其中包含“ZOOM”一词:

import requests
from bs4 import BeautifulSoup

 html = requests.get(
'http://www.adidas.it/scarpe-superstar/C77124.html').text
 bs = BeautifulSoup(html)
 possible_links = bs.find_all('img')
 for link in possible_links:
  if link.has_attr('src'):
    if link.has_key('src'):
        if 'zoom' in link['src']:
            print link['src']

但是我搜索了一个方法来自动抓取一个列表

非常感谢

我尝试这样做以获得列表:

from bs4 import BeautifulSoup
import requests

 url = "http://www.adidas.it/on/demandware.static/-/Sites-adidas-IT-Library/it_IT/v/sitemap/product/adidas-IT-it-it-product.xml"

r = requests.get(url)

data = r.text

soup = BeautifulSoup(data)

for url in soup.findAll("loc"):
print url.text

但我无法附加请求..

我可以在 sitemap.xml 中的任何链接中找到“Zoom”一词

非常感谢

【问题讨论】:

  • 你的问题是……
  • 更新有问题的代码而不是评论。

标签: python xml python-2.7 web-scraping beautifulsoup


【解决方案1】:
import requests
from bs4 import BeautifulSoup
import re

def make_soup(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'lxml')
    return soup
# put urls in a list
def get_xml_urls(soup):
    urls = [loc.string for loc in soup.find_all('loc')]
    return urls
# get the img urls
def get_src_contain_str(soup, string):
    srcs = [img['src']for img in soup.find_all('img', src=re.compile(string))]
    return srcs
if __name__ == '__main__':
    xml = 'http://www.adidas.it/on/demandware.static/-/Sites-adidas-IT-Library/it_IT/v/sitemap/product/adidas-IT-it-it-product.xml'
    soup = make_soup(xml)
    urls = get_xml_urls(soup)
    # loop through the urls
    for url in urls:
        url_soup = make_soup(url)
        srcs = get_src_contain_str(url_soup, 'zoom')
        print(srcs)

【讨论】:

  • 好的,但是要在文件 xml 中查找单词?在这个adidas.it/on/demandware.static/-/Sites-adidas-IT-Library/it_IT/… 中,我必须在文件 xml 中的任何链接中搜索“Zoom”这个词 :) 非常感谢
  • 打印 0 因为我在每个链接中搜索存在 xml 并在此更新中打印带有单词 Zoom 的 img 我在链接地址中的 xml 中搜索单词 zoom.. 但不在每个打开的链接内
  • 很难解释 :D 抱歉,站点地图中的每个链接都包含一个网页 --- 在每个链接中,我必须打开并搜索“zoom”一词
猜你喜欢
  • 2015-05-27
  • 2023-03-22
  • 2022-08-14
  • 2015-10-31
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多