如何从网页中检索这些元素?

2024-04-24 14:40:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下元素的HTML网页:

<div class="content_page">
    <a href="/earth" class="nametessera" >earth</a>
</div>
<div class="content_page">
    <a href="/world" class="nametessera" >world</a>
</div>
<div class="content_page">
    <a href="/planet" class="nametessera">planet</a>
</div>
...

我需要找回地球,世界,行星等等。 所以我需要用类“nametsera”检索标签A的所有链接。在

如何使用python实现这一点?在


Tags: div元素网页地球worldhtmlpage世界
2条回答

简短回答:

使用beautifulSoup解析页面,获取URL,然后使用urlib2pycurl下载提到的URL。在

[编辑:]

添加到下面的示例中,但只使用div中包含的href

>>> alldiv = soup.findAll('div', { "class" : "content_page" })
>>> for div in alldiv: print div.a
... 
<a href="/earth" class="nametessera">earth</a>
<a href="/world" class="nametessera">world</a>
<a href="/planet" class="nametessera">planet</a>
>>> for div in alldiv: print div.a['href']
... 
/earth
/world
/plan

同样,你也可以这样做

^{pr2}$

使用Beautiful Soup解析HTML。在

文档是here。在

相关问题 更多 >