python實現新浪新聞爬蟲

2021-09-01 11:26:39 字數 1934 閱讀 7311

將爬取的新聞**儲存到資料夾e:/sinanews/中,成功後直接通過瀏覽器開啟。

import urllib.request

import re

data=urllib.request.urlopen('').read()

data2=data.decode('utf-8','ignore')#加第二個引數ignore

pat ='href="(.*?)">'

allurl=re.compile(pat).findall(data2)

for i in range(0,len(allurl)):

try:

print('第'+ str(i)+'次爬取')

thisurl=allurl[i]

file='e:/sinanews/'+ str(i)+'.html'

urllib.request.urlretrieve(thisurl,file)

print('...成功....!')

except urllib.error.urlerror as e:

if hasattr(e,'code'): #判斷是否有狀態碼

print(e.code)

if hasattr(e,'reason'):#判斷是否有原因這個屬性

print(e.reason)

import urllib.request

import re

url=''

opener=urllib.request.build_opener()#新增報頭資訊

opener.addheaders=[headers]

data=opener.open(url).read()

#data=urllib.request.urlopen('').read()

data2=data.decode('utf-8','ignore')#加第二個引數ignore

print(len(data2))

pat ='href="(.*?)"'

allurl=re.compile(pat).findall(data2)

for i in range(0,len(allurl)):

try:

print('第'+ str(i)+'次爬取')

thisurl=allurl[i]

file='e:/sinanews/'+ str(i)+'.html'

urllib.request.urlretrieve(thisurl,file)

print('...成功....!')

except urllib.error.urlerror as e:

if hasattr(e,'code'): #判斷是否有狀態碼

print(e.code)

if hasattr(e,'reason'):#判斷是否有原因這個屬性

print(e.reason)

第二種方式,將將opener新增到全域性,都可以使用。

import urllib.request

import re

url=''

opener=urllib.request.build_opener()#新增報頭資訊

opener.addheaders=[headers]

urllib.request.install_opener(opener)#將opener新增到全域性,urlopen(url)可用

data=urllib.request.urlopen(url).read().decode('utf-8','ignore')

pat ='爬取之後,儲存到資料夾中的如圖所示。

python爬蟲獲取新浪新聞教學

一提到python,大家經常會提到爬蟲,爬蟲近來興起的原因我覺得主要還是因為大資料的原因,大資料導致了我們的資料不在只存在於自己的伺服器,而python語言的簡便也成了爬蟲工具的首要語言,我們這篇文章來講下爬蟲,爬取新浪新聞 1 大家知道,爬蟲實際上就是模擬程式設計客棧瀏覽器請求,然後把請求到的資料...

爬蟲學習 爬蟲之新浪新聞

學習資料參考 python網路爬蟲實戰 源程式如下 import requests import json from bs4 import beautifulsoup import pandas results zturl res requests.get zturl jd json.loads r...

新浪新聞小偷

新浪新聞小偷 1.新浪 新聞抓取程式 host 127.0.0.1 mysql 主機名 namesql mysql 使用者名稱 passsql mysql 密碼 lib news 資料庫名 table news 資料庫表名 filename 抓取的新聞頁 key distop 新聞開始 新聞開始關鍵...