首页 > 解决方案 > 遍历 URL 列表并抓取 tspan 元素

问题描述

我想知道是否有一种方法可以遍历 URL 列表,并从每个 URL 导入名为“tspan”的 HTML 元素。

我怎样才能做到这一点?非常感谢。

标签: pythonpython-2.7

解决方案


BeautifulSoup 如果您已经下载了页面的源代码,则可以使用html。否则,使用urllib.request.urlopen获取页面的来源。

from bs4 import BeautifulSoup as bs

html = """
<div>
    <g transform="translate(-128.8249969482422,-7.941666603088379)"> 
        <text text-anchor="left" style="; fill:#000;"> 
            <tspan dy="1em" </tspan> 
    </text> 
    </g>
    <g transform="translate(-128.8249969482422,-7.941666603088379)"> 
        <text text-anchor="left" style="; fill:#000;"> 
            <tspan dy="1em" 2</tspan> 
    </text> 
    </g>
</div>"""

soup = bs(html)

tspans = soup.find_all("tspan")
tspans
[<tspan dy="1em" x="1"></tspan>,
 <tspan dy="1em" x="1"></tspan>]

texts = [tspan.text for tspan in tspans]
texts

推荐阅读