Python網絡爬蟲(5)糗事百科段子抓取

def get_html(url):
    try:
        html = urlopen(url)
    except HTTPError as e:
        print(e)
        return None
    except URLError as e:
        print(e)
        return None
    try:
        bsObj = BeautifulSoup(html,"html.parser")
        return bsObj
    except AttributeError as e:
        print(e)
        return None
 

這個打開煎蛋網的函數打不開糗事百科 因爲有對爬蟲的限制

讓網絡機器人看起來像人類用戶
網站防採集的前提就是要正確地區分人類訪問用戶和網絡機器人。雖然網站可以使用很多識別技術(比如驗證碼)來防止爬蟲,但還是有一些十分簡單的方法,可以讓你的網絡機器人看起來更像人類訪
問用戶。
修改請求頭
在第 9 章裏,我們曾經用 requests 模塊處理網站的表單。requests 模塊還是一個設置請求頭的利器。HTTP 的請求頭是在你每次向網絡服務器發送請求時,傳遞的一組屬性和配置信息。HTTP 定義
了十幾種古怪的請求頭類型,不過大多數都不常用。只有下面的七個字段被大多數瀏覽器用來初始化所有網絡請求(表中信息是我自己瀏覽器的數據)。
屬性內容
Host https://www.google.com/
Connection keep-alive
Accept text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Referrer https://www.google.com/
Accept-Encoding gzip,deflate,sdch
Accept-Language en-US,en;q=0.8
經典的 Python 爬蟲在使用 urllib 標準庫時,都會發送如下的請求頭:

屬性 內容
Accept-Encoding  identity
User-Agent            Python-urllib/3.4

如果你是一個防範爬蟲的網站管理員,你會讓哪個請求頭訪問你的網站呢?
Talk is cheap,show the code!

from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
import urllib.request
import re
import os
import requests
def get_html(url):
    session = requests.Session()
    headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)AppleWebKit 537.36 (KHTML, like Gecko) Chrome","Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
    req = session.get(url, headers=headers)
    bsObj = BeautifulSoup(req.text,"html.parser")
    return bsObj

def get_msg(bsObj):
    for each in bsObj.findAll("div",{"class":"content"}):
        print(each.span.get_text())


if __name__ == "__main__":
    html = get_html("http://www.qiushibaike.com/8hr/page/2/?s=4946249")
    get_msg(html)



OK 可以打開顯示了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章