美文网首页
利用BeautifulSoup抓取腾讯新闻存入MySQL数据库

利用BeautifulSoup抓取腾讯新闻存入MySQL数据库

作者: 小小一只肥羊 | 来源:发表于2018-05-13 20:39 被阅读0次

一、准备
创建MySQL数据库,并创建数据表用于保存抓取到的数据
结构如下:


image.png

创建语句:

CREATE TABLE `news` (
  `id` int(10) NOT NULL,
  `title` varchar(80) NOT NULL,
  `types` varchar(20) NOT NULL,
  `content` mediumtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

二、代码及说明

#!/usr/bin/python3
# coding:utf-8

# 引入相关模块
import pymysql
import requests
from bs4 import BeautifulSoup

#要抓取的网站及抓取到的新闻类型
#可以使用以下四组中任一组url和types(type)

#url = "http://mil.qq.com/mil_index.htm"
#types = "军事"

#url = "http://news.qq.com/world_index.shtml"
#types = "国际"

#url = "http://society.qq.com/"
#types = "社会"

url = "http://cul.qq.com/"
types = "文化"

#声明新闻正文内容,默认为空(会将抓取到的数据复制给它)
content =""

# 请求腾讯新闻的URL,获取其text文本
wbdata = requests.get(url).text
# 对获取到的文本进行解析
soup = BeautifulSoup(wbdata,'lxml')
# 从解析文件中通过select选择器定位指定的元素,返回一个列表
news_titles = soup.select("div.content > em > a.linkto")

# 打开数据库连接
db = pymysql.connect("localhost", "root", "", "news",use_unicode=True, charset="utf8")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 对返回的列表进行遍历
for n in news_titles:
    # 提取出标题和链接信息
    title = n.get_text()#标题
    link = n.get("href")#标题对应正文的链接
    #使用headers声明自己的设备信息(本次要抓取的站点不写也可以)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36',
        'referer': "http://news.qq.com/"}
    html=requests.get("http:"+link,headers=headers).text
    soup1 = BeautifulSoup(html, 'lxml')
    contents = soup1.find_all('p')#正文内容存在p标签中

    for p in contents:
        p=p.get_text()
        content+="&nbsp;&nbsp;&nbsp;&nbsp;"+str(p).replace(u'\u3000',u'')+"<br>" #让抓取到的数据在显示时可以正常段首缩进和换行

    #插入数据建库
    sql = "INSERT INTO news(title,types, content)VALUES ('%s', '%s','%s')"%(str(title),str(types),str(content))
    cursor.execute(sql)
    db.commit()
    content = ""

    #打印插入的新闻的标题
    print(title)

三、说明
只是简单的实现了自己需要内容的抓取(少量简单数据的抓取),代码存在很多需要改进的地方。

相关文章

网友评论

      本文标题:利用BeautifulSoup抓取腾讯新闻存入MySQL数据库

      本文链接:https://www.haomeiwen.com/subject/vfxrdftx.html