beautifulsoup 基本語法 含class屬性查找小技巧class_


案例一:

#coding=utf-8
import json
import requests
from bs4 import BeautifulSoup
url = 'http://www.itest.info/courses' # 定義被抓取頁面的url
soup = BeautifulSoup(requests.get(url).text, 'html.parser')# 獲取被抓取頁面的html代碼(注意這里是用 request框架獲取的頁面源碼),並使用html.parser來實例化BeautifulSoup,屬於固定套路
for course in soup.find_all('h4'):# 遍歷頁面上所有的h4標簽
  print course.text.encode('utf-8')# 打印出h4標簽的text字符    如: 測試開發--試驗班
  print course  # 打印出h4的text字符加標簽    如:<h4>測試開發--試驗班</h4>

 

案例二:

圖例:

 

url = 'https://www.v2ex.com/'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
for span in soup.find_all('span', class_='item_hot_topic_title'):#查找span標簽 且樣式為class_='item_hot_topic_title',注意是class_,不是class,因為class是python的關鍵字,所以后面要加個尾巴,防止沖突
  print span.find('a').text.encode('utf-8')#獲取里面的a標簽展示,假如span標簽里面有很多a標簽,可以 for i in span.find_all('a', href='/t/415664')繼續篩選
  print span.find('a')['href'].encode('utf-8') #獲取href屬性,在bs4里,我們可以通過[attribute_name]的方式來獲取元素的屬性


免責聲明!

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



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