Python 簡單爬蟲抓取糗事百科

來源:互聯網
上載者:User

標籤:linux   爬蟲   python   

# coding:utf-8


import time
import random
import urllib2
from bs4 import BeautifulSoup

#引入 beautifulsoup模組

#p = 1

#定義 頁
url = ‘http://www.qiushibaike.com/text/page/‘
#定義header

my_headers = [
    ‘Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0‘,
    ‘Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)‘,
    ‘Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)‘,
    ‘ELinks/0.12pre5 (textmode; Linux; -)‘
]


#擷取網頁內容
def get_con(url, headers):
    random_header = random.choice(headers)
    req = urllib2.Request(url)
    req.add_header(‘User-Agent‘, random_header)
    req.add_header(‘Host‘, ‘www.qiushibaike.com‘)
    req.add_header(
        ‘Referer‘, ‘http://www.qiushibaike.com/‘)
    req.add_header(‘GET‘, ‘url‘)
    content = urllib2.urlopen(req).read()
    return content

#讀取每一條資訊

def get_txt(haha):
    soup = BeautifulSoup(haha)
    all_txt = soup.find_all(‘div‘, class_="content")
    i = 1
    for txt in all_txt:
        cont = str(txt)
        head = cont.find(r‘class="content"‘)
        end = cont.find(r‘</div‘, head)
        con = cont[head + 16:end]
        print str(i), con
        i = i + 1
        time.sleep(3)

#根據輸入的數字,確定列印起始頁

page = raw_input("Please input a number:")
p = int(page)


#使用while迴圈列印出所有資訊
while p < 36:
    haha = get_con(url + str(p) + ‘?s=4796159‘, my_headers)
    print get_txt(haha)
    print "這是第" + str(p) + "頁"
    p = p + 1
   

本文出自 “World” 部落格,請務必保留此出處http://xiajie.blog.51cto.com/6044823/1682355

Python 簡單爬蟲抓取糗事百科

聯繫我們

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