原文鏈接: iOS程序員如何使用python寫網路爬蟲
以前看到葉孤城寫的iOS程序員如何使用python寫網路爬蟲一文,就寫了一個爬蟲練練手,
最近發現原文章的用的Beautiful Soup 3 目前已經停止開發,推薦在現在的項目中使用Beautiful Soup 4
爬的網站連接都不能用了,寫下我這邊修改的一些東西,僅供參考
歡迎大家來吐槽
<pre>
$sudo pip install beautifulsoup4 或
$sudo easy_install beautifulsoup4 </p>
需要注意的是初始化的時候要使用 BeautifulSoup(html, "html.parser")
</pre>
使用的主網站連接:千圖網
頁面結構布局如下圖,主要是<div class='show-area-pic'
然后拿到其中的img即可了
具體的一些操作細節可以參考iOS程序員如何使用python寫網路爬蟲一文,我就不多贅述了,默認是保存在桌面上新建了一個58pic的文件夾里,也可以修改一下存到sqlite里,也很簡單的,以后再更新
詳細代碼如下:
<pre>
--coding:utf-8--
! /usr/bin/python
import math
import urllib
import urllib2
import os
import request
import sqliteManager
import sys
from bs4 import BeautifulSoup;
def getAllImageLink(start,end):
i = start
path = os.path.expanduser(r'~/Desktop/')
folder = '58pic'
fullPath = path + folder
os.chdir(path)
if os.path.exists(fullPath) == False :
os.mkdir(folder)
else:
# print (unicode('已經存在文件夾: rosi','utf-8'))
print ('has exist')
os.chdir(fullPath)
mainPath = os.getcwd()
while (i < end):
os.chdir(mainPath)
url = 'http://www.58pic.com/yuanchuang/%d.html' % i
try:
response=urllib2.urlopen(url,data=None,timeout=120)
# response=.get(url)
except urllib2.URLError as e:
print ('%s : %s' % (url,e.reason))
i += 1
continue
print (url)
html = response.read()
if html.strip()=='':
print ('not exist URL: %s',url)
continue
soup = BeautifulSoup(html, "html.parser")
liResult = soup.findAll('div',attrs={"class":"show-area-pic"})
for li in liResult:
imageEntityArray = li.findAll('img')
for image in imageEntityArray:
title = image.get('title')
href = image.get('src')
splitList = href.split('/')
fileSavePath = mainPath + '/' + str(splitList[len(splitList) - 1])
urllib.urlretrieve(href,fileSavePath)
print (fileSavePath)
i = i + 1
if __name__ == '__main__':
start = 19840500
getAllImageLink(start,start + 100)
</pre>