如何使用python爬取知乎热榜Top50数据
作者:小狐狸梦想去童话镇 发布时间:2021-11-13 05:47:09
标签:python,爬取知乎,网络爬虫
1、导入第三方库
import urllib.request,urllib.error #请求网页
from bs4 import BeautifulSoup # 解析数据
import sqlite3 # 导入数据库
import re # 正则表达式
import time # 获取当前时间
2、程序的主函数
def main():
# 声明爬取网页
baseurl = "https://www.zhihu.com/hot"
# 爬取网页
datalist = getData(baseurl)
#保存数据
dbname = time.strftime("%Y-%m-%d", time.localtime()) #
dbpath = "zhihuTop50 " + dbname
saveData(datalist,dbpath)
3、正则表达式匹配数据
#正则表达式
findlink = re.compile(r'<a class="css-hi1lih" href="(.*?)" rel="external nofollow" rel="external nofollow" ') #问题链接
findid = re.compile(r'<div class="css-blkmyu">(.*?)</div>') #问题排名
findtitle = re.compile(r'<h1 class="css-3yucnr">(.*?)</h1>') #问题标题
findintroduce = re.compile(r'<div class="css-1o6sw4j">(.*?)</div>') #简要介绍
findscore = re.compile(r'<div class="css-1iqwfle">(.*?)</div>') #热门评分
findimg = re.compile(r'<img class="css-uw6cz9" src="(.*?)"/>') #文章配图
4、程序运行结果
5、程序源代码
import urllib.request,urllib.error
from bs4 import BeautifulSoup
import sqlite3
import re
import time
def main():
# 声明爬取网页
baseurl = "https://www.zhihu.com/hot"
# 爬取网页
datalist = getData(baseurl)
#保存数据
dbname = time.strftime("%Y-%m-%d", time.localtime())
dbpath = "zhihuTop50 " + dbname
saveData(datalist,dbpath)
print()
#正则表达式
findlink = re.compile(r'<a class="css-hi1lih" href="(.*?)" rel="external nofollow" rel="external nofollow" ') #问题链接
findid = re.compile(r'<div class="css-blkmyu">(.*?)</div>') #问题排名
findtitle = re.compile(r'<h1 class="css-3yucnr">(.*?)</h1>') #问题标题
findintroduce = re.compile(r'<div class="css-1o6sw4j">(.*?)</div>') #简要介绍
findscore = re.compile(r'<div class="css-1iqwfle">(.*?)</div>') #热门评分
findimg = re.compile(r'<img class="css-uw6cz9" src="(.*?)"/>') #文章配图
def getData(baseurl):
datalist = []
html = askURL(baseurl)
# print(html)
soup = BeautifulSoup(html,'html.parser')
for item in soup.find_all('a',class_="css-hi1lih"):
# print(item)
data = []
item = str(item)
Id = re.findall(findid,item)
if(len(Id) == 0):
Id = re.findall(r'<div class="css-mm8qdi">(.*?)</div>',item)[0]
else: Id = Id[0]
data.append(Id)
# print(Id)
Link = re.findall(findlink,item)[0]
data.append(Link)
# print(Link)
Title = re.findall(findtitle,item)[0]
data.append(Title)
# print(Title)
Introduce = re.findall(findintroduce,item)
if(len(Introduce) == 0):
Introduce = " "
else:Introduce = Introduce[0]
data.append(Introduce)
# print(Introduce)
Score = re.findall(findscore,item)[0]
data.append(Score)
# print(Score)
Img = re.findall(findimg,item)
if (len(Img) == 0):
Img = " "
else: Img = Img[0]
data.append(Img)
# print(Img)
datalist.append(data)
return datalist
def askURL(baseurl):
# 设置请求头
head = {
# "User-Agent": "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36(KHTML, likeGecko) Chrome/80.0.3987.163Safari/537.36"
"User-Agent": "Mozilla / 5.0(iPhone;CPUiPhoneOS13_2_3likeMacOSX) AppleWebKit / 605.1.15(KHTML, likeGecko) Version / 13.0.3Mobile / 15E148Safari / 604.1"
}
request = urllib.request.Request(baseurl, headers=head)
html = ""
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
# print(html)
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
print()
def saveData(datalist,dbpath):
init_db(dbpath)
conn = sqlite3.connect(dbpath)
cur = conn.cursor()
for data in datalist:
sql = '''
insert into Top50(
id,info_link,title,introduce,score,img)
values("%s","%s","%s","%s","%s","%s")'''%(data[0],data[1],data[2],data[3],data[4],data[5])
print(sql)
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
def init_db(dbpath):
sql = '''
create table Top50
(
id integer primary key autoincrement,
info_link text,
title text,
introduce text,
score text,
img text
)
'''
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
conn.close()
if __name__ =="__main__":
main()
来源:https://blog.csdn.net/gets_s/article/details/115096619
0
投稿
猜你喜欢
- 一、yaml文件介绍yaml是一个专门用来写配置文件的语言。1. yaml文件规则区分大小写;使用缩进表示层级关系;使用空格键缩进,而非Ta
- 用户管理是绝大部分Web网站都需要解决的问题。用户管理涉及到用户注册和登录。用户注册相对简单,我们可以先通过API把用户注册这个功能实现了:
- gjsonGJSON 是一个Go包,它提供了一种从json文档中获取值的快速简单的方法。它具有单行检索、点符号路径、迭代和解析 json 行
- 手机控件查看工具uiautomatorviewer工具简介用来扫描和分析Android应用程序的UI控件的工具.如何使用 1.进入
- 正文开始if name == "main":可以看成是python程序的入口,就像java中的main()方法,但不完全
- 对于python,这几天一直有两个问题在困扰我:1.python中没办法直接取得当前的行号和函数名。这是有人在论坛里提出的问题,底下一群人只
- 参考:1.Basemap绘制中国地图2.Basemap生成的图中绘制轨迹使用CMA热带气旋最佳路径数据集,对我国周边的台风进行绘制impor
- SQLServer中建立与服务器的连接时出错的解决方案如下:步骤1:在SQLServer 实例上启用远程连接1.指向“开始->程序-&
- 按单词反转字符串是一道很常见的面试题。在Python中实现起来非常简单。def reverse_string_by_word(s): lst
- Date 日期和时间对象1. 介绍Date对象,是操作日期和时间的对象。Date对象对日期和时间的操作只能通过方法。2. 构造函数2.1 n
- 一、使用安装pip install mitmproxymitmproxy 是具有控制台界面的交互式,支持SSL的拦截代理mitmdump是m
- 这篇文章主要介绍了python实现XML解析的方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋
- Go语言拼接URL路径有多种方法建议用ResolveReference。JoinPathJoinPath会把多个多个路径合并成一个路径,并且
- 前言:python 中协程概念是从 3.4 版本增加的,但 3.4 版本采用是生成器实现,为了将协程和生成器的使用场景进行区分,使语义更加明
- Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列Lifo
- 一、概论C4.5主要是在ID3的基础上改进,ID3选择(属性)树节点是选择信息增益值最大的属性作为节点。而C4.5引入了新概念“信息增益率”
- 今早打开 腾讯ISD的博客 ,看到一篇新的文章,《迷你屋视觉规范简介》,赶紧看了来学习。不过给我抓到问题咯,臭鱼不介意我在这说下吧:这套规范
- 要了解JavaScript对象,我们可以从对象创建、属性操作、对象方法这几个方面入手。概括起来,包括以下几模块: 1.
- 目录process模块1、在python中启动一个子进程2、给子进程传递参数3、同时开多个子进程4、join的用法5、多进程之间的数据是否隔
- 1.SQL SERVER的数据类型 数据类弄是数据的一种属性,表示数据所表示信息的类型。任何一种计算机语言都定义了自己的数据类型。当然,不同