python3爬取数据至mysql的方法

yipeiwu_com5年前Python爬虫

本文实例为大家分享了python3爬取数据至mysql的具体代码,供大家参考,具体内容如下

直接贴代码

#!/usr/local/bin/python3.5 
# -*- coding:UTF-8 -*- 
from urllib.request import urlopen 
from bs4 import BeautifulSoup 
import re 
import datetime 
import random 
import pymysql 
 
connect = pymysql.connect(host='192.168.10.142', unix_socket='/tmp/mysql.sock', user='root', passwd='1234', db='scraping', charset='utf8') 
cursor = connect.cursor() 
cursor.execute('USE scraping') 
 
random.seed(datetime.datetime.now()) 
 
 
def store(title, content): 
 
  execute = cursor.execute("select * from pages WHERE `title` = %s", title) 
  if execute <= 0: 
    cursor.execute("insert into pages(`title`, `content`) VALUES(%s, %s)", (title, content)) 
    cursor.connection.commit() 
  else: 
    print('This content is already exist.') 
 
 
def get_links(acticle_url): 
  html = urlopen('http://en.wikipedia.org' + acticle_url) 
  soup = BeautifulSoup(html, 'html.parser') 
  title = soup.h1.get_text() 
  content = soup.find('div', {'id': 'mw-content-text'}).find('p').get_text() 
  store(title, content) 
  return soup.find('div', {'id': 'bodyContent'}).findAll('a', href=re.compile("^(/wiki/)(.)*$")) 
 
links = get_links('') 
 
try: 
  while len(links) > 0: 
    newActicle = links[random.randint(0, len(links) - 1)].attrs['href'] 
    links = get_links(newActicle) 
    print(links) 
finally: 
  cursor.close() 
  connect.close() 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

用Python编写简单的微博爬虫

用Python编写简单的微博爬虫

先说点题外话,我一开始想使用Sina Weibo API来获取微博内容,但后来发现新浪微博的API限制实在太多,大家感受一下: 只能获取当前授权的用户(就是自己),而且只能返回最新的...

python2使用bs4爬取腾讯社招过程解析

目的:获取腾讯社招这个页面的职位名称及超链接 职位类别 人数 地点和发布时间 要求:使用bs4进行解析,并把结果以json文件形式存储 注意:如果直接把python列表没有序列化为jso...

Python3网络爬虫之使用User Agent和代理IP隐藏身份

Python3网络爬虫之使用User Agent和代理IP隐藏身份

本文介绍了Python3网络爬虫之使用User Agent和代理IP隐藏身份,分享给大家,具体如下: 运行平台:Windows Python版本:Python3.x IDE...

Python 爬虫学习笔记之多线程爬虫

Python 爬虫学习笔记之多线程爬虫

XPath 的安装以及使用 1 . XPath 的介绍 刚学过正则表达式,用的正顺手,现在就把正则表达式替换掉,使用 XPath,有人表示这太坑爹了,早知道刚上来就学习 XPath 多省...

python书籍信息爬虫实例

python书籍信息爬虫示例,供大家参考,具体内容如下 背景说明 需要收集一些书籍信息,以豆瓣书籍条目作为源,得到一些有效书籍信息,并保存到本地数据库。 获取书籍分类标签 具体可参考这个...