Python爬蟲
爬取騰訊新聞首頁的新聞內容
最近學習了爬蟲,爬了一些內容,分享一下,方便大家,
import urllib.request
import urllib.error
import re,ssl
#例外處理
try:
#針對https ,需要單獨處理
#import ssl
#ssl._create_default_https_context = ssl._create_unverified_context
ssl._create_default_https_context = ssl._create_unverified_context
url="https://xw.qq.com/"
#該部分通過用戶代理(User-Agent)來模擬瀏覽器請求
#headers=("User-Agent"," Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Mobile Safari/537.36")
#opener=urllib.request.build_opener()
#opener.addhesders=[headers]
#date=opener.open(url).read().decode("utf-8","ignore")
date=urllib.request.urlopen(url).read().decode("utf-8","ignore")
#正則運算式,提取所需的資訊(即新聞鏈接)
pat=''',"url":"(.*?)",'''
#全域匹配函式,把提取出來的資訊放入串列中
thislink=re.compile(pat).findall(date)
#列印該串列,可不要
print(thislink)
for i in range(len(thislink)):
#判斷字串"http"是否在提取出的鏈接中
if ("http" in thislink[i]):
#通過urlretrieve()直接把鏈接放入本地
urllib.request.urlretrieve(thislink[i],"D:/write1/date/"+str(i)+".html")
else:
#沒有"http"時,通過手動添加鏈接頭,此時針對了https
urllib.request.urlretrieve("https://xw.qq.com"+thislink[i],"D:/write1/date/"+str(i)+".html")
#HTTPError有兩個屬性,例外原因和例外狀態碼
except urllib.error.HTTPError as e:
#列印例外狀態碼
if hasattr(e.code):
print(e.code)
#列印例外原因
if hasattr(e.reason):
print(e.reason)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/274739.html
標籤:python
上一篇:抓取淘寶網商品資訊
