python BeautifulSoup4--例子


from bs4 import BeautifulSoup
import requests
import re

#請求博客園首頁
r=requests.get('http://www.cnblogs.com/tangqiu/')

#使用html.parser解析html
soup=BeautifulSoup(r.content,'html.parser')
print(soup.name) #soup.name 為[document]

#使用正則表達式找出所有以t開頭的標簽,返回一個列表
t=soup.find_all(re.compile('^t'))

#從t列表中找到title,使用.string 獲取html的標題
for title in t:
    print(title.string)

#找出所有class="dayTitle"的標簽,返回一個列表
tags=soup.find_all(class_="dayTitle")

#打印首頁博客的日期
for time in tags:
    print(time.a.string)

#打印首頁博客的摘要
abstract=soup.find_all(class_="c_b_p_desc")
for abstract in abstracts:
    print(abstract.contents[0])

 中文官方文檔http://beautifulsoup.readthedocs.io/zh_CN/latest/


免責聲明!

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



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