python bs4的使用


# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup as bs
import re

html_doc = """
<html><head><title>The Dormouse's story<a>試試</a></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=bs(html_doc,'html.parser')

# 獲取網頁內容
# print(soup.prettify())


# #獲取網頁的title
# print(soup.title)
#
# #H獲取網頁title的內容,獲取id為link2的內容,若標簽中還有標簽,則返回值為None,這時就可以用.get_text()來獲取結果
# print(soup.title.string)
# print(soup.title.get_text())

#獲取第一個a標簽
# print(soup.a)
#
#
# print(soup.find(id='link2').string)

#
# #獲取所有的a標簽,並返回列表
# print(soup.findAll('a'))
#
#
# #獲取class為story的p標簽,且不能像find(id='**')來獲取,因為class為python的關鍵字
# print(soup.find('p',{'class':'story'}).get_text())

#
# for tag in soup.find_all(re.compile("^b")):
#     print(tag.name)






data=soup.findAll('a',href=re.compile(r'^http://example\.com'))

print(data)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM