首页 > 解决方案 > 在中找不到关键字组合xml中的标记

问题描述

我想找到一个包含<loc>两个关键字的标签。例如,我想找到一个<loc>包含“Yankee”“duck”的标签。代码如下:

elif len(keywords) == 2:
    keyword1 = keywords[0]
    keyword2 = keywords[1]

    print("Searching for product...")
    keywordLinkFound = False
    while keywordLinkFound is False:
        html = self.driver.page_source
        soup = BeautifulSoup(html, 'lxml')
        try:
            keywordLink = soup.find('image:title', text=re.compile(keyword1 + keyword2)).text
            return keywordLink
        except AttributeError:
            print("Product not found on site, retrying...")
            time.sleep(monitorDelay)
            self.driver.refresh()
        break

这是我想要得到的 xml:

<url>
<loc>
  https://packershoes.com/products/copy-of-382-packer-x-new-era-new-york-yankee-duck-canvas-1
</loc>
<lastmod>2018-12-06T14:39:37-05:00</lastmod>
<changefreq>daily</changefreq>
<image:image>
<image:title>
  NEW ERA JAPAN 59FIFTY NEW YORK YANKEES "DUCK CANVAS"
</image:title>
</image:image>
</url>

标签: pythonbeautifulsoupxml-parsingkeyword

解决方案


我会在搜索功能中执行此操作,因为它可以让您“更多”地控制搜索条件:

def desired_tags(tag):
    text = tag.get_text()

    return tag.name == 'image:title' and \
           'Yankee' in text and 'duck' in text

results = soup.find_all(desired_tags)

推荐阅读