簡單的網路爬蟲的python實現

2021-07-30 13:52:34 字數 1919 閱讀 8280

# coding=utf-8

import htmlparser

import urllib

import sys

import re

import os

# 定義html解析器

class parselinks(htmlparser.htmlparser):

# 該方法用來處理開始標籤的,eg:def handle_starttag(self, tag, attrs):

def _attr(attrlist, attrname):

for each in attrlist:

if attrname == each[0]:

return each[1]

return none

if tag == 'a' or tag == "li" or tag == "link": # 如果為標籤

# name為標籤的屬性名,如href、name、id、onclick等等

for name, value in attrs:

if name == 'href': # 這時選擇href屬性

#print "name_value: ", value # href屬性的值

link_file.write(value)

link_file.write("\n")

#print "title: ", _attr(attrs, 'title')

#print "first tag:", self.get_starttag_text() # 標籤的開始tag

#print "\n"

def search_info(link, key):

name = key

text = urllib.urlopen(link).read()

file_object = open("text.txt", "w")

file_object.write(text)

file_object.close()

file_read = open("text.txt", "r")

for line in file_read:

if re.search(name, line):

print line

file_result.write(line)

file_result.write("\n")

file_read.close()

def deep_search(link, depth):

lparser.feed(urllib.urlopen(link).read())

if __name__ == "__main__":

#處理輸入

key = raw_input("請輸入需要搜尋的關鍵字: ")

print "我知道了主人,您需要找關鍵字:", key

# 建立html解析器的例項

lparser = parselinks()

# 深度搜尋子鏈結

link_file = open("sub_link.txt", "w")

deep_search("", 10)

link_file.close()

# 查詢子鏈結中的資訊

python的實現原理 python爬蟲實現原理

前言 簡單來說網際網路是由乙個個站點和網路裝置組成的大網,我們通過瀏覽器訪問站點,站點把html js css 返回給瀏覽器,這些 經過瀏覽器解析 渲染,將豐富多彩的網頁呈現我們眼前 一 爬蟲是什麼?如果我們把網際網路比作一張大的蜘蛛網,資料便是存放於蜘蛛網的各個節點,而爬蟲就是乙隻小蜘蛛,二 爬蟲...

爬蟲實戰 3初學Python網路爬蟲(5個例項)

要爬取的頁面為 如下 import requests defgethtmltext url try r requests.get url,timeout 30 r.raise for status 如果狀態不是200,引發httperror異常 print r.status code print r...

Python 簡單的爬蟲

爬取的資料是 豆瓣電影top250 使用的python庫有 requests bs4的beautifulsoup pandas。通過requests爬取網頁資料,通過beautifulsoup解析網頁資料,通過pandas將資料儲存成excel csv格式。import requests 爬取資料 ...