首页 技术 正文
技术 2022年11月12日
0 收藏 944 点赞 4,786 浏览 5758 个字

Python–(爬虫与数据库的连接)

(每一天都是属于你的!)

Python对于初学后巩固基础的人还是更多的来接触python爬虫会更好一些,在Python爬虫中包含很多基础部分知识,并且在项目中会提升你的成功感!加油!

我在工作之余时间,把Python的爬虫基础内容整理了一下,资料因为太多所以都放在QQ群内了,需要的可以来—607021567。

今天整理了一个两个网站的小说阅读平台的爬虫,将两个网站的小说可按自有的格式抓取下来自动生成txt文件。

项目介绍:

  –Python爬虫

    –模块:requests,BeautifulSoup,time

    –分析:request模块作用于网站的连接与处理,BeautifulSoup作用于源码中的代码分析与抓取,time主要是在我们抓取的过程中加入时间限制(这个主要是应对有网站监控的,这里我们就不需要了)

因为这里没有涉及到数据库相关的操作,所以没有对数据库的相关详细内容,但是我会将Python与mongodb、MySQL、Sqlserver的连接方式的代码会附赠在下面。

一、网页分析:

首先步步分析网页内容:https://www.booktxt.net/6_6453/2529786.html,cookie信息–F12键。

这里面有很多广告,不过可以不用去理它们,首先获取到我们需要的网址:

 # -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
import time def project(url,page):
#url='http://www.23us.so/files/article/html/1/1809/877404.html' #大主宰
#url='http://www.23us.so/files/article/html/6/6100/2193573.html' #天下无双
#url='https://www.booktxt.net/6_6453/2529786.html' #元尊
headers={"Cookie": "jieqiVisitId=article_articleviews%3D6453; cscpvrich87",
"Host": "www.booktxt.net",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}
r =requests.get(url,headers,timeout=30)
h = r.content

这里主要使用request模块获取网址的源码,h–就是我们所获取的源码,你可以测试的时候print出来。

二、源码分析

我们这里直接在网页中来查看源码:网页中右键查看源码。

这里我们注意到文本的内容包含在<div id=”content”>的标签内,所以接下来我们使用bs4来处理。

 soup = BeautifulSoup(h, "html.parser")
a1 = soup.find('div',class_="bookname").h1
text_da(a1.get_text().encode('utf-8')+'\n\n\n')
a = soup.find('div',id='content')
text_da(a.get_text().encode('utf-8')+'\n\n\n')

每一行分开解释:

1、使用BeautifulSoup模块,其中”html.parser”是模块内置函数,对源码的分析,这样我们就获取到网址的bs4源码。

2、首先是获取小说中的标题,soup.find–是获取源码中第一个div标签class=“bookname”下的h1标签,当前我们获取到h1标签所有内容包括标签,但是我们需要获取到文本内容。

3、获取获得标签内的文本内容–a1.get_text(),这里的encode(‘utf-8’)是将我们获取的内容需要转码,不然是乱码的状态。

4、获取我们主要的文本内容–同理,需要获得文本内容的标签div

5、获得文本内容。

三、分页操作

因为我们浏览的页面会有分页,所有这里也是我们需要注意的地方。

Python–(爬虫与数据库的连接)

Python–(爬虫与数据库的连接)

这里的下一章按钮,就是我们的突破点:

  b = soup.find('div',class_='bottem2')
if b:
a = b.find_all('a')
#shuurl = 'http://www.23us.so'+a[-1]['href']
shuurl = 'https://www.booktxt.net' + a[-2]['href']
#print shuurl
page=page+1
project(shuurl,page)

我们在源码中获取到的下一章的网址位于a标签内。

3行、–我们获取所有的a标签。

5行、a[-2]是获取我们倒数第二个标签也就是我们的下一章标签,【’href‘】–是获得a标签内的href的内容也就是我们的地址,这里需要拼接字符串。

7行、是抓取的注释内容,稍后在源码中你会看到效果

8行、有的小伙伴注意到了,这里是调用函数,函数的名字就是我们一开始定义的函数,就是它自己本身。

四、写入文件

接下来,我们的主要价值数据获取到,但是我们需要它成为txt文件,所以我写了一个函数,在上面的函数体中直接调用就可以了。

 def text_da(text):
fo = open("foo.txt", "a")
fo.write(text) # 关闭打开的文件
fo.close()

五、启动函数

最后一步,就是我们的启动程序代码。

 if __name__ == '__main__':
page=1
url = 'https://www.booktxt.net/6_6453/2529786.html' # 元尊
project(url,page)

这里主要是python的内置函数,作为启动py文件内的函数。

六、源码

哦!忘了源码—–

 # -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
import time def project(url,page):
#url='http://www.23us.so/files/article/html/1/1809/877404.html' #大主宰
#url='http://www.23us.so/files/article/html/6/6100/2193573.html' #天下无双
#url='https://www.booktxt.net/6_6453/2529786.html' #元尊
headers={"Cookie": "jieqiVisitId=article_articleviews%3D6453; cscpvrich8793_fidx=4; __tins__19219364=%7B%22sid%22%3A%201527749231776%2C%20%22vd%22%3A%204%2C%20%22expires%22%3A%201527751067272%7D; __51cke__=; __51laig__=4; Hm_lvt_6949867c34e7741ebac3943050f04833=1527749232; Hm_lpvt_6949867c34e7741ebac3943050f04833=1527749267; cscpvcouplet8792_fidx=4; cscpvrich8791_fidx=4",
"Host": "www.booktxt.net",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}
r =requests.get(url,headers,timeout=30)
h = r.content
#print h
soup = BeautifulSoup(h, "html.parser")
#a = soup.find('dd',id='contents')
#print a.get_text()
a1 = soup.find('div',class_="bookname").h1
text_da(a1.get_text().encode('utf-8')+'\n\n\n')
a = soup.find('div',id='content')
text_da(a.get_text().encode('utf-8')+'\n\n\n')
print '第'+str(page)+'章!'
#b = soup.find('dd',id='footlink')
b = soup.find('div',class_='bottem2')
if b:
a = b.find_all('a')
#shuurl = 'http://www.23us.so'+a[-1]['href']
shuurl = 'https://www.booktxt.net' + a[-2]['href']
#print shuurl
page=page+1
project(shuurl,page) def text_da(text):
fo = open("foo.txt", "a")
fo.write(text) # 关闭打开的文件
fo.close() if __name__ == '__main__':
page=1
url = 'https://www.booktxt.net/6_6453/2529786.html' # 元尊
project(url,page)

对了!还有Python对于数据库的连接操作,我这里直接就贴源码了,其中很多的内容我都注释了!不懂的可以加群—607021567(需要验证信息,因为我不知道来的是朋友还是敌人)

 # -*- coding:utf-8 -*-
import pymongo
from pymongo import MongoClient
import json
#MONGODB
#连接
client = MongoClient('mongodb://localhost')
db = client.test
table='test'
#db[table].insert({'user_id':2,'name':'zhu'})
#db[table].update({'name':'zhu'},{'$set':{'user_id':2}})
#db[table].remove({'name':'zhu'})
#查询结果排序(key:1或者-1)升序或者降序
a = db[table].find().sort("user_id",1)
print a
for i in a:
print i #db.authenticate('test','test') """table = 'imi_product'
a = db[table].find({'partno':'NEN1FX6'}).limit(1)
detailList = []
for i in a:
if (i.get("specs")):
specary = i.get("specs")
for i in specary:
detailList.append({"left": i, "right": specary[i]})
print detailList
for i in detailList:
print i.get('right')
#查询和增加
#db[table].insert({'sn':1,'b':'b'})
#更改
#db[table].update({'sn':1},{'$set':{'b':'sda'}})
#删除
#删除name=lisi的全部记录
#db[table].remove({'sn': 1})
#删除集合里的所有记录
#db.users.remove()
# (>) 大于 - $gt
# (<) 小于 - $lt
# (>=) 大于等于 - $gte
# (<= ) 小于等于 - $lte
#a = db[table]
#print a.find_one()""" #SQLSERVER
"""import pyodbc
import MySQLdb
MSSQL_INFO = {"hostname":"localhost","username":"","password":"","dbname":"oneice"}
strconn= 'DRIVER={SQL Server};SERVER='+MSSQL_INFO.get("hostname")+';DATABASE='+MSSQL_INFO.get("dbname")+';UID='+MSSQL_INFO.get("username")+';PWD='+MSSQL_INFO.get("password")
db = pyodbc.connect(strconn)
sqldb = db.cursor()
#查询
sql = 'select * from news where news_id=1'
#添加
sql ="insert into news (news_title,news_author,news_summary,news_content,news_pic) values ('haha','happy','Iriji','little','12dsa')"
#删除
sql ="delete from news where news_id=5"
sqldb.execute(sql)
sqldb.commit()
#查询
row = sqldb.fetchone()
print row[1]
#存储过程
sqldb.execute("{call 存储过程名字 (参数)}", '上传的参数')
q = sqldb.fetchone()/fetchall()
sqldb.commit()
if q:
print q[1]"""

这里包含这Python调用SQLSERVER的存储过程和基本操和MONGODB的基本操作!

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295