scrapy基礎 之 爬蟲入門:先用urllib2來跑幾個爬蟲

1,爬取糗事百科html

概況:糗事百科是html網頁,支持直接抓取html字符而後用正則過濾正則表達式

           爬取糗事百科須要同時發送代理信息,即user-agent服務器

import urllib2,re

def pachong(page):
    url="http://www.qiushibaike.com/hot/page/"+str(page)    #起始頁
    user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'    #代理信息,可經過f12查看
    headers={'User-Agent':user_agent}    #把代理信息按照合理方式編輯到headers中
    try:
        request=urllib2.Request(url,headers=headers)    #url後邊加headers參數,發送帶headers的訪問請求
        response=urllib2.urlopen(request)    #以網頁方式打開服務器給的response
        content=response.read().decode('utf-8')    #編碼方式是utf-8,沒有編碼方式的設置不能得出正確答案
        pattern=re.compile('<span>\s*(.*)\s*</span>')    #正則表達式過濾信息
        items=re.findall(pattern,content)    #findall造成的是一個列表,列表的元素是全部匹配的字符串
        for i in items:
            haveimg=re.search('img',i)    #過濾掉圖片格式內容
            if not haveimg:
                print i,'\n'
    except Exception as e:
        print e

if __name__=='__main__':
    for i in range(1,3):
        pachong(i)
相關文章
相關標籤/搜索