python網絡數據採集 wiki貝肯數6代碼

編程語言 Python Pages Links C加加 2017-04-29

今天給大家帶來的是wiki貝肯數6的代碼,大家可以評論一下哪裡需要改的

from bs4 import BeautifulSoup

from urllib.request import urlopen

import re

import pymysql

conn = pymysql.connect(host = '127.0.0.1',port = 3306, user = 'root', passwd = '12345', db = 'mysql', charset = 'utf8')

cur = conn.cursor()

cur.execute("use wikipedia") # 使用數據庫wikipedia

def insertPageIfNotExists(url): # page表

cur.execute("select * from pages where url = %s",(url)) #根據半截url鏈接查找

if cur.rowcount == 0: #使用cur.rowcount獲取結果集的條數,如果是0

cur.execute("insert into pages (url) values (%s)",(url)) # 將此url插入數據庫

想要一起學習python的可以加群556982049,群裡有大量學習資料,還有大神解答問題,你們可以訂閱轉發一下

conn.commit()

return cur.lastrowid # 最後插入行的主鍵???

else: # 如果查詢到了數據

return cur.fetchone()[0] # fetchone()取得結果集的下一行,返回一個單獨的序列,沒有可用數據則返回None,這裡[0]項是id

def insertLink(fromPageId,toPageId): # links表

cur.execute("select * from links where fromPageId = %s and toPageId = %s",(int(fromPageId),int(toPageId)))

if cur.rowcount == 0:

cur.execute("insert into links (fromPageId,toPageId) values(%s,%s)",(int(fromPageId),int(toPageId)))

conn.commit()

pages = set()

def getLinks(pageUrl,recursionLevel):

global pages

if recursionLevel > 4: # 如果遞歸次數大於4

return;

pageId = insertPageIfNotExists(pageUrl) # 返回pages表裡的數據的id號

html = urlopen("http://en.wikipedia.org"+pageUrl) # http://en.wikipedia.org/wiki/Kevin_Bacon

bsObj = BeautifulSoup(html,'html.parser')

for link in bsObj.findAll("a",href = re.compile("^(/wiki/)((?!:).)*$")): # 找到當前詞條頁面內所有/wiki開頭的詞條鏈接

# 將頁內鏈接存入pages,返回id,然後將兩個id存入links表

insertLink(pageId,insertPageIfNotExists(link.attrs['href'])) # insertPageIfNotExists(link.attrs['href'])返回href在pages表裡的id號

if link.attrs['href'] not in pages: # 如果href鏈接沒有保存過

# 遇到一個新頁面,加入集合並搜索裡面的詞條鏈接

newPage = link.attrs['href']

pages.add(newPage)

getLinks(newPage,recursionLevel+1) # 遞歸,次數+1

getLinks("/wiki/Kevin_Bacon", 0)

cur.close()

conn.close()

python網絡數據採集 wiki貝肯數6代碼

想要一起學習python的可以加群556982049,群裡有大量學習資料,還有大神解答問題,你們可以訂閱轉發一下

相關推薦

推薦中...