python爬蟲入門 初步採集

2021-07-25 20:49:46 字數 1375 閱讀 1237

#獲取維基百科**的任何頁面並提取頁面鏈結 

import urllib2

import bs4

html = urllib2.urlopen("")

bsobj = bs4.beautifulsoup(html.read(), "lxml")

for link in bsobj.find("a"):

if 'href' in link.attrs:

print(link.attrs['href'])

以上**問題:存在不需要的鏈結,如側邊欄、頁首、頁尾的各種鏈結。
所需要鏈結的特點:
所以利用正規表示式進行篩選,改進版:
import urllib2

import bs4

import re

html = urllib2.urlopen("")

bsobj = bs4.beautifulsoup(html.read(), "lxml")

#利用正規表示式篩選出了不必要的鏈結

for link in bsobj.find("div", ).findall("a", href=re.compile("^(/wiki/)((?!:).)*$")):

if 'href' in link.attrs:

print(link.attrs['href'])

繼續改進:

import urllib2

import bs4

import re

import datetime

import random

random.seed(datetime.datetime.now())

def getlinks(articleurl):

html = urllib2.urlopen(""+articleurl)

bsobj = bs4.beautifulsoup(html.read(), "lxml")

return bsobj.find("div", ).findall("a", href=re.compile("^(/wiki/)((?!:).)*$"))

links = getlinks("/wiki/kevin_bacon")

while len(links) > 0:

newarticle = links[random.randint(0, len(links)-1)].attrs["href"]

print(newarticle)

links = getlinks(newarticle)

python爬蟲入門初步認識

python簡單的爬蟲技術,這裡我用的是python3.x版面進行研究,主要對兩個python庫進行操作。在此之前你需要安裝python3.x環境 1 urllib python3.x官方基礎模組 2 beautifulsoup4 python3.x第三方模組 使用前需要安裝beautifulsou...

python 爬蟲 網路資料採集 入門知識

1 正規表示式符號與方法 常用符號 匹配任意字元,換行符 除外 匹配前乙個字元0次或無限次 匹配前乙個字元0次或1次 貪心演算法 非貪心演算法 括號內的資料作為結果返回 2 正規表示式符號與方法 常用方法 findall 匹配所有符合規律的內容,返回包含結果的列表 search 匹配並提取第乙個符合...

初步嘗試python爬蟲

一直想學習爬蟲 直到最近兩天 才開始了學習 以下嘗試了requests和beautifulsoup的基本用法 抓取了豆瓣新書速遞的 並以書名對進行命名 請各位看官多多指教 如果有人看的話 import requests from bs4 import beautifulsoup as bs url ...