在写爬虫之前需要先配置python环境,爬取静态网页的文字及图片只需要通过pip安装Scrapy、beautifulsoup4 。(此处略去一万字,可以自行百度python3爬虫框架)
一定要注意python代码的格式化!
一般网站都会有反爬虫机制,所以我们在这里使用最简单的方法构建header头。
header={'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0'}
还可以用代理IP防止网站因访问速度太快封IP。对于代理IP我们可以直接百度”代理IP“进行查找。
url1 = request.Request(url,headers=header)
#建立代理IP列表,此处去百度查代理IP。此处IP只是示例!!!!
iplist = ['61.135.217.7:80','115.223.223.132:9000']
proxies = {'http':random.choice(iplist)}
proxy_support = urllib.request.ProxyHandler(proxies)
#创建opener
opener = urllib.request.build_opener(proxy_support)
#安装opener,此后调用urlopen()时都会使用安装过的opener对象
urllib.request.install_opener(opener)
之后要用到BeautifulSoup。对于BeautifulSoup可以用Python标准库,这种方法速度快简单但是容错差。此处就是利用标准库
soup = BeautifulSoup(html,'html.parser')
对于爬虫的一个关键就是通过正则表达式获取到所需的内容。此处的代码作用是爬取图片,!!!!对于不同网站正则表达式会有差异!!!!在此处是认为图片的标签是img。之后用正则表达式获取到图片的源地址并存入列表,便于一个一个爬取保存下载。如有不懂正则表达式的可以在菜鸟教程中学习或留言交流交流。
links = soup.find_all('img',src=re.compile(r'.jpg$'))
之后就是简单的遍历下载了。此处有一个坑就是需要再打开图片的源地址,对于这个页面我们的header头又变成了python的初始header,这个时候服务器认出这是爬虫,如果此网站恰巧不想被爬就会关闭连接,此时程序就会抛出403异常。此时我们将每个需要访问的网址加上header就会正常了
for link in links:
print(link.attrs['src'])
url_real='https:'+link.attrs["src"]
print(url_real)
header={'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0'}
url_real = request.Request(url_real,headers=header)
data = urllib.request.urlopen(url_real).read()
with open(path+'\%s.jpg' % time.time(), 'wb') as f:
f.write(data)
pass
到此为止,你的爬虫就能使用了。
说了这么多是时候上代码了:
from bs4 import BeautifulSoup
import urllib.request
from urllib import request
import re
import time
import random
import requests
print('输入网址:',end="")
url = input('')
header={'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0'}
#抛出异常
try:
url1 = request.Request(url,headers=header)
iplist = ['XXX.XXX.XXX.XXX:XXXX','XXX.XXX.XXX.XXX:XXXX','115.223.223.132:9000\
']
proxies = {'http':random.choice(iplist)}
proxy_support = urllib.request.ProxyHandler(proxies)
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
html = urllib.request.urlopen(url1).read()#.decode('utf-8') 若显示乱码则将加上编码
soup = BeautifulSoup(html,'html.parser')
links = soup.find_all('img',src=re.compile(r'.jpg$'))
path = r'F:\编程语言Learning\Python\test\images'
for link in links:
print(link.attrs['src'])
url_real='https:'+link.attrs["src"]
print(url_real)
header={'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0'}
url_real = request.Request(url_real,headers=header)
data = urllib.request.urlopen(url_real).read()
with open(path+'\%s.jpg' % time.time(), 'wb') as f:
f.write(data)
pass
except urllib.error.URLError as e:
print(e.reason)