BeautifulSoup入门案例
生活随笔
收集整理的這篇文章主要介紹了
BeautifulSoup入门案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import beautifulsoup4 as bsimport requestsurl = "http://www.baidu.com"html = requests.get(url) # 獲取網頁響應對象html.encoding = 'utf-8' # 修改網頁響應對象(requests.models.Response)的編碼格式content = html.text # 獲取網頁的內容soup = bs(content, 'html.parser') # 根據網頁內容創(chuàng)建一個beautifulsoup對象, 'html.parser'為網頁解析器print(soup.prettify()) # 格式化輸出網頁內容a_tag_set = soup.find_all('a') # 獲取網頁中的所有的a標簽,返回值為一個集合a_tag = soup.find('a') # 獲取網頁中的第一個a標簽a_tag = soup.a # 獲取網頁中的第一個a標簽a_dict = a_tag.attrs # 獲取a標簽的屬性字典print(a_dict['href']) # 打印a標簽中的'href'屬性的值a_parent_tag_iterator = soup.a.parent # .parent返回可迭代對象,不是列表,需要用for循環(huán)遍歷其中的內容a_children_tag_iterator = soup.a.children # .children返回可迭代對象,不是列表,需要用for循環(huán)遍歷其中的內容
總結
以上是生活随笔為你收集整理的BeautifulSoup入门案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iphone计算机快捷键,苹果电脑快捷键
- 下一篇: mysql 5.0.37.tar.gz_