python3 BeautifulSoup模塊使用字典的方法抓取a標(biāo)簽內(nèi)的數(shù)據(jù)示例
本文實(shí)例講述了python3 BeautifulSoup模塊使用字典的方法抓取a標(biāo)簽內(nèi)的數(shù)據(jù)。分享給大家供大家參考,具體如下:
# -*- coding:utf-8 -*- #python 2.7 #XiaoDeng #http://tieba.baidu.com/p/2460150866 #標(biāo)簽操作 from bs4 import BeautifulSoup import urllib.request import re #如果是網(wǎng)址,可以用這個(gè)辦法來讀取網(wǎng)頁 #html_doc = "http://tieba.baidu.com/p/2460150866" #req = urllib.request.Request(html_doc) #webpage = urllib.request.urlopen(req) #html = webpage.read() html=""" <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a rel="external nofollow" rel="external nofollow" class="sister" id="xiaodeng"><!-- Elsie --></a>, <a rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and <a rel="external nofollow" class="sister" id="link3">Tillie</a>; <a rel="external nofollow" rel="external nofollow" class="sister" id="xiaodeng">Lacie</a> and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html, 'html.parser') #文檔對象 #查找a標(biāo)簽,只會查找出一個(gè)a標(biāo)簽 #print(soup.a)#<a class="sister" rel="external nofollow" rel="external nofollow" id="xiaodeng"><!-- Elsie --></a> for k in soup.find_all('a'): print(k) print(k['class'])#查a標(biāo)簽的class屬性 print(k['id'])#查a標(biāo)簽的id值 print(k['href'])#查a標(biāo)簽的href值 print(k.string)#查a標(biāo)簽的string #如果,標(biāo)簽中含有其他標(biāo)簽,比如..,此時(shí)要提取中的數(shù)據(jù),需要用k.get_text() #tag.get('calss'),也可以達(dá)到這個(gè)效果 Python Socket編程技巧總結(jié)》、《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python實(shí)現(xiàn)矩陣轉(zhuǎn)置的幾種方法詳解
這篇文章主要介紹了Python實(shí)現(xiàn)矩陣轉(zhuǎn)置的幾種方法詳解,zip() 函數(shù)用于將可迭代的對象作為參數(shù),將對象中對應(yīng)的元素打包成一個(gè)個(gè)元組,然后返回由這些元組組成的對象,這樣做的好處是節(jié)約了不少的內(nèi)存,需要的朋友可以參考下2023-08-08Python如何快速生成本項(xiàng)目的requeirments.txt實(shí)現(xiàn)
本文主要介紹了Python如何快速生成本項(xiàng)目的requeirments.txt實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03numpy.random.choice()函數(shù)詳解
處理數(shù)據(jù)時(shí)我們經(jīng)常需要從數(shù)組中隨機(jī)抽取元素,這時(shí)候我們可以考慮使用np.random.choice()函數(shù),這篇文章主要介紹了numpy.random.choice()函數(shù),需要的朋友可以參考下2023-05-05Python入門學(xué)習(xí)之字符串與比較運(yùn)算符
這篇文章主要介紹了Python入門學(xué)習(xí)之字符串與比較運(yùn)算符,是Python語法中的基礎(chǔ)知識,需要的朋友可以參考下2015-10-10Python實(shí)現(xiàn)定時(shí)備份mysql數(shù)據(jù)庫并把備份數(shù)據(jù)庫郵件發(fā)送
這篇文章主要介紹了Python實(shí)現(xiàn)定時(shí)備份mysql數(shù)據(jù)庫并把備份數(shù)據(jù)庫郵件發(fā)送的相關(guān)資料,需要的朋友可以參考下2018-03-03Python腳本開發(fā)中的命令行參數(shù)及傳參示例詳解
這篇文章主要為大家介紹了Python腳本開發(fā)中的命令行參數(shù)及傳參示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07