python爬虫之pymysql库的使用(2)
来源:互联网 发布:centos安装hadoop2.6 编辑:程序博客网 时间:2024/06/06 05:51
要想使用pymysql库,要先安装,因为这是第三方库。
同样,可使用pip大法。安装过程就不说了,比较简单。
下面通过实例来说明这个库和爬虫的结合使用:
from urllib.request import urlopenfrom bs4 import BeautifulSoupimport re #导入正则表达式库import datetimeimport randomimport pymysqlconfig = { 'host':'localhost', 'port':3306, 'user':'root', 'password':'root', 'db':'scraping', 'charset':'utf8' } # 'charset':'' #设置编码格式 conn=pymysql.connect(**config)cur=conn.cursor() #使用连接对象获得一个cursor(光标)对象#cursor提供的方法包括两大类:1.执行命令,2.接收返回值# execute(self, query,args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数# fetchone(self):返回一条结果行.# fetchall(self):接收全部的返回结果行.random.seed(datetime.datetime.now()) #随即种子(当前时间)def store(title,content):cur.execute("INSERT INTO pages (title,content) VALUE (%s,%s)",(title,content))cur.connection.commit() #提交保存修改过的数据def getLinks(articleUrl):html=urlopen("http://en.wikipedia.org"+articleUrl)bsObj=BeautifulSoup(html,"html.parser")title=bsObj.find("h1").get_text()content=bsObj.find("div",{"id":"mw-content-text"}).find("p").get_text()store(title,content)return bsObj.find("div",{"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$"))links=getLinks("/wiki/Kevin_Bacon")try:while len(links)>0:newAricle = links[random.randint(0,len(links)-1)].attrs['href']print(newAricle)links = getLinks(newAricle)finally:cur.close()conn.close()用完数据库记得关闭光标和连接对象,以防数据泄漏
阅读全文
0 0
- python爬虫之pymysql库的使用(2)
- python爬虫之pymysql库的使用(1)
- mySQL之pymysql的使用
- Python数据库之--PyMySQL
- python的pymysql
- python操作数据库之pymysql
- python操作mysql之pymysql
- python使用pymysql操作mysql
- Python爬虫入门三之Urllib库的基本使用
- Python爬虫入门三之Urllib库的基本使用
- Python爬虫入门三之Urllib库的基本使用
- Python爬虫入门一之Urllib库的基本使用
- Python爬虫入门1之urllib库的使用
- Python爬虫入门三之Urllib库的基本使用
- Python爬虫入门三之Urllib库的基本使用
- python爬虫入门三之Urllib库的基本使用
- Python爬虫入门之Urllib库的基本使用 (三)
- Python爬虫之Beautiful Soup库的安装与使用
- 关于lua垃圾回收器的理解
- C#转换国内省市区,文本内容来自某area.json文件
- 免安装版MySQL(3)修改初始密码命令
- Springboot filter 拦截指定的路径(注入spring Bean方式)
- leetcode 67. Add Binary
- python爬虫之pymysql库的使用(2)
- Java实习生在项目中遇到的问题
- Java实现验证码的制作
- android studio 汉化包 美化包
- Xamarin Studio
- 数据结构与算法(3)---Java语言实现:栈的单链表定义
- SQL优化之四两拨千金
- Tkinter之Event篇
- 浏览器兼容性总结以及处理