python爬取文章執行個體教程

來源:互聯網
上載者:User
這篇文章主要跟大家介紹了利用python爬取散文網文章的相關資料,文中介紹的非常詳細,對大傢具有一定的參考學習價值,需要的朋友們下面來一起看看吧。

本文主要給大家介紹的是關於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><p id="one"><a></a></p><p id="two"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >abc</a></p><p 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></p><p 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></p></body></html>

然後test.py的代碼為:


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

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


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

接下來就是通過requests 擷取網頁資訊了,我不太懂別人為什麼要寫heard跟其他的東西

我直接進行網頁訪問,通過get方式擷取散文網幾個分類的二級網頁然後通過一個組的測試,把所有的網頁爬取一遍


def get_html(): url = "https://www.sanwen.net/" two_html = ['sanwen','shige','zawen','suibi','rizhi','novel'] for doc in two_html: i=1  if doc=='sanwen':  print "running sanwen -----------------------------"  if doc=='shige':  print "running shige ------------------------------"  if doc=='zawen':  print 'running zawen -------------------------------'  if doc=='suibi':  print 'running suibi -------------------------------'  if doc=='rizhi':  print 'running ruzhi -------------------------------'  if doc=='nove':  print 'running xiaoxiaoshuo -------------------------' while(i<10): par = {'p':i} res = requests.get(url+doc+'/',params=par) if res.status_code==200:  soup(res.text)  i+=i

這部分的代碼中我沒有對res.status_code不是200的進行處理,導致的問題是會不顯示錯誤,爬取的內容會有丟失。然後分析散文網的網頁,發現是www.sanwen.net/rizhi/&p=1

p最大值是10這個不太懂,上次爬盤多多是100頁,算了算了以後再分析。然後就通過get方法擷取每頁的內容。

擷取每頁內容以後就是分析作者跟題目了代碼是這樣的


def soup(html_text): s = BeautifulSoup(html_text,'lxml') link = s.find('p',class_='categorylist').find_all('li') for i in link: if i!=s.find('li',class_='page'): title = i.find_all('a')[1] author = i.find_all('a')[2].text url = title.attrs['href'] sign = re.compile(r'(//)|/') match = sign.search(title.text) file_name = title.text if match: file_name = sign.sub('a',str(title.text))

擷取標題的時候出現坑爹的事,請問大佬們寫散文你標題加斜杠幹嘛,不光加一個還有加兩個的,這個問題直接導致我後面寫入檔案的時候檔案名稱出現錯誤,於是寫Regex,我給你改行了吧。

最後就是擷取散文內容了,通過每頁的分析,獲得文章地址,然後直接擷取內容,本來還想直接通過改網頁地址一個一個的獲得呢,這樣也省事了。


def get_content(url): res = requests.get('https://www.sanwen.net'+url) if res.status_code==200: soup = BeautifulSoup(res.text,'lxml') contents = soup.find('p',class_='content').find_all('p') content = '' for i in contents: content+=i.text+'\n' return content

最後就是寫入檔案儲存ok


 f = open(file_name+'.txt','w') print 'running w txt'+file_name+'.txt' f.write(title.text+'\n') f.write(author+'\n') content=get_content(url)  f.write(content) f.close()

三個函數擷取散文網的散文,不過有問題,問題在於不知道為什麼有些散文丟失了我只能擷取到大概400多篇文章,這跟散文網的文章是差很多很多的,但是確實是一頁一頁的擷取來的,這個問題希望大佬幫忙看看。可能應該做網頁無法訪問的處理,當然我覺得跟我宿舍這個破網有關係


 f = open(file_name+'.txt','w') print 'running w txt'+file_name+'.txt' f.write(title.text+'\n') f.write(author+'\n') content=get_content(url)  f.write(content) f.close()

差點忘了


能會出現timeout現象吧,只能說上大學一定要選網好的啊!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.