python实现一个栏目的分页抓取列表页抓取

python实现一个栏目的分页抓取列表页抓取

#!/usr/bin/env python
# coding=utf-8

import requests
from bs4 import BeautifulSoup
import pymysql

import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') # Change default encoding to utf8

print('连接到mysql服务器...')
db = pymysql.connect("localhost","root","root","python")
print('连接上了!')
cursor = db.cursor()

hdrs = {'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)'}


def has_class_but_no_id(tag):
    return tag.has_attr('title') and tag.has_attr('href') and not tag.has_attr('target')

urls = ['http://www.zztez.com/tezgl/list_1_{}.html'.format(str(i)) for i in range(5,11)]

for url in urls:
    print(url)
    r = requests.get(url, headers = hdrs)
    soup = BeautifulSoup(r.content.decode('gbk', 'ignore'), 'lxml')

    for link in soup.find_all(has_class_but_no_id):
                url="http://www.zztez.com" + link.get('href')
                r = requests.get(url, headers = hdrs)
                soup = BeautifulSoup(r.content.decode('gbk', 'ignore'), 'lxml')

                title=soup.find("h1")
                title=title.string.encode("utf-8")

                intro=soup.select(".intro")
                rintro=intro[0].string.encode("utf-8")

                content=soup.select(".content")
                rcontent=content[0].encode("utf-8")

                #查询数据
                sql="SELECT count(*) as total FROM article WHERE title like %s"
                data=(title)
                row_affected=cursor.execute(sql,data)
                one=cursor.fetchone()

                if one==(0,):
                    insert = ("INSERT INTO article(title,intro,content)" "VALUES(%s,%s,%s)")
                    data = (title, rintro, rcontent)
                    cursor.execute(insert, data)
                    db.commit()

print('爬取数据并插入mysql数据库完成...')

 

posted on 2017-10-27 17:14  baker95935 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/baker95935/p/7744308.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值