您的位置:首页 > 编程语言 > Python开发

python爬虫学习第二十三天

2017-08-16 21:42 381 查看
今天的内容与MySQL有关

MySQL是当今使用最广泛的关系式数据库,具体请到他们的官网查看

首先是用命令行操作数据库,利用这个过程来熟悉MySQL。

CREATE DATABASE scraping

USE scraping

CREATE TABLE pages(

id BIGINT(7) NOT NULL AUTO_INCREMENT,

title VARCHAR(200),

content VARCHAR(10000),

created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

PRIMARY KEY(id))

ALTER TABLE pages

CHANGE content content VARCHAR(20000)

接下来,python与MySQL结合

使用python操作mysql需要下载第三方库pyMySQL,这个项目在GitHub上开源,并且最新版本已经支持使用pip命令安装。

下载完成后就可以开始实验。

练习1 连接数据库

连接(conn) / 光标(cur)模式是数据库编程中常用的模式,一个连接可以有很多个光标。个光标跟踪一种状态(state)信息,比如跟踪数据库的 使用状态。如果你有多个数据库,且需要向所有数据库写内容,就需要多个光标来处理。 光标还会包含最后一次查询执行的结果。通过调用光标函数,比如 cur.fetchone(),可以 获取查询结果。光标与链接使用完成后一定要关闭,否则会造成连接泄漏。

# import pymysql

# conn = pymysql.Connect(user='root',password='Gaoji1996',db='mysql')
# cur = conn.cursor()
# cur.execute('USE scraping')
# cur.execute('SELECT* FROM pages WHERE id=1')
# print(cur.fetchone())
# cur.close()
# conn.close()


练习2 使用数据库接收维基百科的各种信息

注意pymysql.connect()函数的参数,里边有一个charset=”utf8”,这是相当重要的,我在一开始写的时候就丢了这个参数,调试失败。还有就是cur.execute()这个函数,里边嵌入的sql语句中所有的字符都要用双引号,mysql不支持单引号,使用单引号调试是失败的。另外生成newArticle时候千万不要忘记了.attrs[‘href’]属性,我一开始粗心大意给忘记了,找了半天错儿

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import random
a9a1
import datetime
import pymysql

conn = pymysql.Connect(user='root',password='Gaoji1996',charset='utf8')
cur = conn.cursor()
cur.execute('use scraping')
random.seed(datetime.datetime.now())

def store(title,content):
cur.execute('INSERT INTO pages(title,content) VALUES(\"%s\",\"%s\")',(title,content))
cur.connection.commit()
pass
def getLinks(articleUrl):
html = urlopen('http://en.wikipedia.org'+articleUrl)
bsObj = BeautifulSoup(html)
title = bsObj.find('h1').get_text()
content = bsObj.find('div',{'id':'mw-content-text'}).find('p').get_text()
store(title,content)
links = bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$"))

return links
pass
links = getLinks('/wiki/Kevin_Bacon')
try:
while len(links)>0:
newArticle = links[random.randint(0,len(links)-1)].attrs['href']
print(newArticle)
links = getLinks(newArticle)
finally:
cur.close()
conn.close()


今天到这里啦,打卡~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python