墨斋记

Good Luck To You!

python BeautifulSoup(待更新)

1、安装

pip install beautifulsoup4

from bs4 import BeautifulSoup

html_doc = """
<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>
"""soup = BeautifulSoup(html_doc, 'html.parser')print(soup.prettify())

#Finding Elements
soup.title
# <title>The Dormouse's story</title>

soup.title.name
# 'title'

soup.title.string
# 'The Dormouse's story'

soup.title.parent.name
# 'head'

soup.p
# <p class="title"><b>The Dormouse's story</b></p>

soup.p['class']
# ['title']

#Searching by Class and ID

soup.find_all('a', class_='sister')
# Returns all <a> tags with class "sister"

soup.find(id="link3")
# Returns the element with id "link3"

#Extracting all URLs

for link in soup.find_all('a'):    
    print(link.get('href'))
    
 #Getting Text
 print(soup.get_text())


发表评论:

Powered By Z-BlogPHP 1.7.3

冀公网安备13019902000834
冀ICP备18019600号-1
Copyright CC Some Rights Reserved.Contact Email:chengyingbo88@163.com