进行数据采集时,我们需要思考的问题时,我们需要的信息是需要下载下来还是只存储一个连接即可。 如果你的信息只用一次,建议只爬取信息连接即可,如果你的信息需要多次重复使用,可以下载下来,防止爬虫失效,但是爬取数据时注意不要对信息提供者造成影响。而且下载还有一个好处,可以让你的爬虫看起来更像浏览器行为。
1.下载文件
下载文件使用urllib.request.urlretrieve,这个函数可以根据url下载文件。当我们想要下载图片时,我们就可以提取图片连接,然后交给这个函数处理,下载到指定的图片。
from urllib.request import urlretrieve
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com")
bs0bj = BeautifulSoup(html)
imageLocation = bs0bj.find("a",{"id": "logo"}).find("img")["src”]
urlretrieve (imageLocation, "logo.jpg")
上面的例子就是从指定的连接下载图片并存为logo.jpg
2.数据存储为csv
csv是表格数据的常用存储格式。下面是创建一个csv的代码:
#参考代码,测试没有通过,可能是csv库修改了
import csv
csvFile = open("../files/test.csv", 'w+')
try:
writer = csv.writer(csvFile)
writer.writerow(('number', 'number plus 2', 'number times 2'))
for i in range(10):
writer.writerow((i,i+2,i^2))
finally:
csvFile.close()
3.存储为MYSQL
mysql是当下最流行的开源关系型数据库,基本上可以满足我们的需求,最新的5.7版本支持json,非常适合作为爬虫存储的仓库。
centos下MYSQL安装教程:http://www.centoscn.com/mysql/2016/0315/6844.html
教程备份:https://yunpan.cn/cPDIwUgJaifiD (提取码:9a27)
安装PyMysql整合python与mysql:
pip install PyMySQL
参考: https://github.com/PyMySQL/PyMySQL/
安装PYmysql后,启动MYSQL,可以执行下面命令测试连接:
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock',user='root', passwd=None, db='mysql')
#启用连接对象(conn)和光标对象(cur)
cur = conn.cursor()
cur.execute("USE scraping")
cur.execute("SELECT * FROM pages WHERE id=1")
print(cur.fetchone())
#关闭cur和conn,使用后必须关闭
cur.close()
conn.close()
下面是从维基百科爬来的程序存入mysql
4.Email
Email使用SMTP协议传输的,假设本机上有一个SMTP客户端。用Python发送一封邮件只需要数行代码:
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("The body of the email is here")
msg['Subject'] = "An Email Alert"
msg['From'] = "ryan@pythonscraping.com"
msg['To'] = "webmaster@pythonscraping.com"
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
参考:https://docs.python.org/3.5/library/email-examples.html