求问网页标签获取

2017-08-17 16:46:46 +08:00
 holajamc

使用 bs4 可以很轻松获得网页文字内容,但是如果想获得网页的标签信息应该怎么做?

假如网页源码是

<html>

<head>
    <title>The Dormouse's story</title>
</head>

<body>
    <p class="title"><b>The Dormouse's story</b></p>

    <p class="story">Once upon a time there were three little sisters; and their names were
        <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
        <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
        <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p>

    <p class="story">...</p>
</body>

</html>

获得网页标签结构

<html>

<head>
    <title> </title>
</head>

<body>
    <p class="title"><b> </b></p>

    <p class="story">
        <a href="http://example.com/elsie" class="sister" id="link1"> </a>
        <a href="http://example.com/lacie" class="sister" id="link2"> </a>
        <a href="http://example.com/tillie" class="sister" id="link3"> </a> </p>

    <p class="story"> </p>
</body>

</html>
1224 次点击
所在节点    Python
1 条回复
Droi
2017-08-18 10:37:58 +08:00
你是不是想要这些内容。
我是熬两次汤,熬出来的。不知道其他人有没有其他好用的方法。
官方教程的快速开始有这个 get()方法

from bs4 import BeautifulSoup
>>> html = """<html> ..... </html>"""
>>> soup = BeautifulSoup(html, "html.parser")
>>> ssoup = BeautifulSoup(str(soup.find_all(attrs={'class':'story'})), "html.parser")
>>> ssoup.find_all('a')[0].get('href')
'http://example.com/elsie'
>>>

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/383734

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX