用python写个小爬虫
来源:互联网 发布:c语言float是什么意思 编辑:程序博客网 时间:2024/06/18 10:30
一时兴起,学着写了个python爬虫,记录一下。
我使用python版本是v3.6.1,主要用来Beautiful Soup库,版本是v4.5.3。爬的是古诗文网(如果古诗文网的小伙伴介意,在此表示抱歉)
代码如下:
#!/usr/bin/pythonimport requestsimport pymysqlimport timefrom bs4 import BeautifulSoupdef insertDb(db, title, str): # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() create_at = time.strftime("%Y%m%d%H%M%S", time.localtime()) sql = "INSERT INTO POETRY(TITLE,CONTENT, CREATE_AT, SOURCE)\ VALUES ('%s', '%s', '%s', '%d')" % (title ,str, create_at, 1) cursor.execute(sql)# 打开数据库连接db = pymysql.connect(host = "localhost", user = "root", passwd = "", db = "test", charset = "utf8")n = 1while(n < 1000): web_url = "http://so.gushiwen.org/view_%s.aspx" % (n) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'} r = requests.get(web_url, headers=headers) title = BeautifulSoup(r.text, 'lxml').find('h1') content = BeautifulSoup(r.text, 'lxml').find('div', id="cont") n = n+1 if not title: continue insertDb(db, title.text, content.text) if not n%50 : print(n) db.commit() time.sleep(1)db.close()
0 0
- 用python写个小爬虫
- python写个小爬虫
- 用python写爬虫
- 用python爬虫
- 用python实现网络爬虫
- 用python编写网页爬虫
- 用Python 爬虫爬取贴吧图片
- 用Python写简单爬虫
- 用Python实现网络爬虫
- 用python写网络爬虫
- 用python实现简单爬虫
- 用python 2运行爬虫
- 用Python写网络爬虫
- python爬虫-->爬虫基础
- [爬虫] Python爬虫技巧
- Python爬虫
- python 爬虫
- python 爬虫
- ConcurrentHashMap的实现原理
- node.js初识-千里之行始于足下
- iOS-UIWebView加载html,文字大小颜色设置,图片自适应设置
- 解决两个虚拟机网络适配器都为NAT模式,其中一台无法上网的情况
- 移动端弹出层上禁止页面滚动
- 用python写个小爬虫
- CKEditor 上传图片到 WebBroker 做的 Web 服务器
- 图像特征检测(Image Feature Detection)
- CSS和HTML中的块元素和内联元素的区别,特点和关系
- win7 打开共享目录提示 —— 登陆失败:未知的用户名或密码错误解决办法
- 计算机视觉之统计形状模型——Active Shape Model
- Mycat开发实践---MyCAT线程模型分析
- /includes/cls_template.php on line 406 Ecshop出现问题
- ROS学习笔记(二):利用opencv将本地图片转换成ROS格式