用Beautiful拿到小說作者和文章(沒有加入cookie元素,比較簡單的完整代碼)
# -*- coding=utf-8 -*-
import urllib2
from bs4 import BeautifulSoup
# 得到網頁源代碼
def download(url,user_agent = 'wswp',proxy = None,num_retries = 2):
print 'downloading:',url
headers = {'User-agent':user_agent} # 設置代理服務
request = urllib2.Request(url,headers = headers) # 發出請求
opener = urllib2.build_opener() # 創建一個opener
# 異常處理
try:
html = opener.open(request).read() # 拿到網頁源代碼
except urllib2.URLError as e:
print 'download error:',e.reason
html = None
if num_retries > 0:
if hasattr(e,'code') and 500 <= e.code < 600:
html = download(url,user_agent,proxy,num_retries-1) # 若是對方服務器問題,則重新爬取,最多再爬兩次
return html
# 得到小說信息
def crawler_info(seed_url):
html = download(seed_url)
soup = BeautifulSoup(html) # 將拿到的網頁源代碼轉換爲BeautifulSoup的格式
title = soup.title # 文章名稱
content = soup.find(id='content') # 文章內容
print '題目:',title.text # 以文本格式輸出
print '文章:',content.text
# 測試
url = 'http://www.biquge5200.com/52_52542/20380548.html'
crawler_info(url)