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使用beautifulsoup4爬取酷狗音乐代码实例

这篇文章主要介绍了python使用beautifulsoup4爬取酷狗音乐代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 小编...

Python爬虫_城市公交、地铁站点和线路数据采集实例

Python爬虫_城市公交、地铁站点和线路数据采集实例

城市公交、地铁数据反映了城市的公共交通,研究该数据可以挖掘城市的交通结构、路网规划、公交选址等。但是,这类数据往往掌握在特定部门中,很难获取。互联网地图上有大量的信息,包含公交、地铁等数...

详解用python写网络爬虫-爬取新浪微博评论

新浪微博需要登录才能爬取,这里使用m.weibo.cn这个移动端网站即可实现简化操作,用这个访问可以直接得到的微博id。 分析新浪微博的评论获取方式得知,其采用动态加载。所以使用json...

Python基于分析Ajax请求实现抓取今日头条街拍图集功能示例

Python基于分析Ajax请求实现抓取今日头条街拍图集功能示例

本文实例讲述了Python基于分析Ajax请求实现抓取今日头条街拍图集功能。分享给大家供大家参考,具体如下: 代码: import os import re import json...

scrapy爬虫实例分享

scrapy爬虫实例分享

前一篇文章介绍了很多关于scrapy的进阶知识,不过说归说,只有在实际应用中才能真正用到这些知识。所以这篇文章就来尝试利用scrapy爬取各种网站的数据。 爬取百思不得姐 首先一步一步来...