python爬虫学习第二十三天

来源:互联网 发布:微信数据备份 编辑:程序博客网 时间:2024/06/07 15:47

今天的内容与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 urlopenfrom bs4 import BeautifulSoupimport reimport randomimport datetimeimport pymysqlconn = 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()    passdef 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    passlinks = 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()

今天到这里啦,打卡~

原创粉丝点击