Python 製作糗事百科爬蟲執行個體_python

來源:互聯網
上載者:User

早上起來閑來無事做,莫名其妙的就彈出了糗事百科的段子,轉念一想既然你送上門來,那我就寫個爬蟲到你網站上爬一爬吧,一來當做練練手,二來也算找點樂子。

其實這兩天也正在接觸資料庫的內容,可以將爬取下來的資料儲存在資料庫中,以待以後的利用。好了,廢話不多說了,先來看看程式爬取的資料結果

值得一提的是,我在程式中想一下子爬取糗事百科 30 頁的內容,但是出現了串連錯誤,當我把頁數降到 20 頁的時候,程式就可以正常的跑起來了,不知道是什麼原因,渴望知道的大神可以告訴我一聲,感激不盡。

程式非常簡單,直接上原始碼咯

# coding=utf8import reimport requestsfrom lxml import etreefrom multiprocessing.dummy import Pool as ThreadPoolimport sysreload(sys)sys.setdefaultencoding('utf-8')def getnewpage(url, total): nowpage = int(re.search('(\d+)', url, re.S).group(1)) urls = [] for i in range(nowpage, total + 1):  link = re.sub('(\d+)', '%s' % i, url, re.S)  urls.append(link) return urlsdef spider(url): html = requests.get(url) selector = etree.HTML(html.text) author = selector.xpath('//*[@id="content-left"]/div/div[1]/a[2]/@title') content = selector.xpath('//*[@id="content-left"]/div/div[2]/text()') vote = selector.xpath('//*[@id="content-left"]/div/div[3]/span/i/text()') length = len(author) for i in range(0, length):  f.writelines('作者 : ' + author[i] + '\n')  f.writelines('內容 :' + str(content[i]).replace('\n','') + '\n')  f.writelines('支援 : ' + vote[i] + '\n\n')if __name__ == '__main__': f = open('info.txt', 'a') url = 'http://www.qiushibaike.com/text/page/1/' urls = getnewpage(url, 20) pool = ThreadPool(4) pool.map(spider,urls) f.close()

如果其中有不懂得部分,可以依次參考我的前三篇文章。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.