博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
爬取维基百科人物介绍,并使用pymysql存储到数据库
阅读量:7097 次
发布时间:2019-06-28

本文共 1844 字,大约阅读时间需要 6 分钟。

代码如下:

from urllib.request import urlopenfrom bs4 import BeautifulSoupimport reimport datetimeimport randomimport pymysql.cursors # Connect to the databaseconnection = pymysql.connect(host='127.0.0.1',                             port=3306,                             user='root',                             password='数据库密码',                             db='scraping',                             charset='utf8mb4',                             cursorclass=pymysql.cursors.DictCursor)cur = connection.cursor()random.seed(datetime.datetime.now())def store(title,content):    cur.execute("INSERT INTO pages(title,content)values(\"%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()    print(title)    content = bsObj.find("div",{
"id":"mw-content-text"}).find("p").get_text() print(content) 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 : newArticle = links[random.randint(0, len(links)-1)].attrs["href"] #print(newArticle) links = getLinks(newArticle)finally: cur.close() connection.close()

结果截图

 

注:

  由于维基百科上我们会遇到各种各样的字符,所以最好通过下面四条语句让数据库支持unicode:

  

    alter database scraping character set = utf8mb4 collate = utf8mb4_unicode_ci;    alter table pages  convert to character set = utf8mb4 collate = utf8mb4_unicode_ci;    alter table pages change title title varchar(200) character set = utf8mb4 collate = utf8mb4_unicode_ci;    alter table pages change content content varchar(10000) character set = utf8mb4 collate = utf8mb4_unicode_ci;

 

转载于:https://www.cnblogs.com/ncuhwxiong/p/7580128.html

你可能感兴趣的文章
linux网络相关配置文件
查看>>
敏捷开发(十一)- Scrum Sprint评审会议
查看>>
UED
查看>>
Hello World 之 控制台版本(Console Application)
查看>>
linux下nginx+php+mysql 自助环境搭建
查看>>
udp通信
查看>>
国家模式c++
查看>>
假设动态运行java文字,当在脚本式配置,这是非常方便的
查看>>
android4.0 的图库Gallery2代码分析(三) 之Applition的初始化准备
查看>>
SOM自组织映射网络 教程
查看>>
lintcode:寻找旋转排序数组中的最小值 II
查看>>
maven项目配置Jetty服务器
查看>>
树莓派学习笔记——交叉编译练习之SQLite3安装
查看>>
android stuido build 慢的解决办法
查看>>
Eclipse 插件安装方法和插件加载失败解决办法
查看>>
第四节:教你如何快速让浏览器兼容ES6特性
查看>>
C#使用IrisSkin2.dll美化WinForm程序界面
查看>>
Appium移动自动化测试(四)--one demo
查看>>
nginx配置location总结及rewrite规则写法
查看>>
python 登陆接口
查看>>