国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

利用python爬取散文網的文章實例教程

2020-02-16 01:42:43
字體:
來源:轉載
供稿:網友

本文主要給大家介紹的是關于python爬取散文網文章的相關內容,分享出來供大家參考學習,下面一起來看看詳細的介紹:

效果圖如下:


配置python 2.7

 bs4 requests

安裝 用pip進行安裝 sudo pip install bs4

sudo pip install requests

簡要說明一下bs4的使用因為是爬取網頁 所以就介紹find 跟find_all

find跟find_all的不同在于返回的東西不同 find返回的是匹配到的第一個標簽及標簽里的內容

find_all返回的是一個列表

比如我們寫一個test.html 用來測試find跟find_all的區別。

內容是:

<html><head></head><body><div id="one"><a></a></div><div id="two"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >abc</a></div><div id="three"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >three a</a><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >three a</a><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >three a</a></div><div id="four"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >four<p>four p</p><p>four p</p><p>four p</p> a</a></div></body></html>

然后test.py的代碼為:

from bs4 import BeautifulSoupimport lxmlif __name__=='__main__': s = BeautifulSoup(open('test.html'),'lxml') print s.prettify() print "------------------------------" print s.find('div') print s.find_all('div') print "------------------------------" print s.find('div',id='one') print s.find_all('div',id='one') print "------------------------------" print s.find('div',id="two") print s.find_all('div',id="two") print "------------------------------" print s.find('div',id="three") print s.find_all('div',id="three") print "------------------------------" print s.find('div',id="four") print s.find_all('div',id="four") print "------------------------------"

運行以后我們可以看到結果當獲取指定標簽時候兩者區別不大當獲取一組標簽的時候兩者的區別就會顯示出來


所以我們在使用時候要注意到底要的是什么,否則會出現報錯

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宝山区| 岳阳县| 澎湖县| 永福县| 兴山县| 晋城| 台江县| 都江堰市| 通州市| 鄯善县| 合川市| 祁门县| 温泉县| 新宁县| 清流县| 武鸣县| 上饶县| 施秉县| 万载县| 阜南县| 中宁县| 兰坪| 大悟县| 措勤县| 米易县| 福建省| 浦北县| 永安市| 双辽市| 左贡县| 衡山县| 建瓯市| 新闻| 合川市| 黑龙江省| 区。| 嵩明县| 墨江| 白朗县| 阿坝县| 阜宁县|