requests爬取知乎话题和子话题
zhihu.py
# *_*coding:utf-8 *_*
import pymysql
import requests
from lxml import etree from requests_test.child_topic import GetChildTopic
from requests_test.parent_topic import GetParentTopic if __name__ == "__main__":
parent = GetParentTopic()
res = parent.get_parent_data()
# child = GetChildTopic()
# child.get_child_data(1027,2)
child = GetChildTopic()
for i in res:
print("parent_id:",i)
child.get_child_data(i,50)
parent_topic.py
# *_*coding:utf-8 *_*
import pymysql
from lxml import etree import requests class GetParentTopic(object):
def __init__(self):
self.conn = pymysql.connect(host='192.168.33.10', user='root', passwd='root', db='spider', charset='utf8')
self.cur = self.conn.cursor() def get_parent_data(self):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}
url = 'https://www.zhihu.com/topics' response = requests.get(url, headers=headers)
res = response.text html = etree.HTML(res)
ul = html.xpath("//ul[@class='zm-topic-cat-main clearfix']/li"); parent_topic = {} for li in ul:
title = li.xpath('./a/text()')[0];
topic_id = li.xpath('./@data-id')[0];
parent_topic[topic_id] = title
import time # 格式化成2016-03-20 11:45:39形式
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 插入数据
sql = "insert ignore into topic(`title`,`topic_id`,`create_time`) values('{}','{}','{}')".format(title,
topic_id, now)
#print(sql)
reCount = self.cur.execute(sql)
self.conn.commit() self.cur.close()
self.conn.close()
return parent_topic
child_topic.py
# *_*coding:utf-8 *_*
import json
import urllib
from time import sleep import pymysql
from lxml import etree
import requests class GetChildTopic(object):
def __init__(self):
self.conn = pymysql.connect(host='192.168.33.10', user='root', passwd='root', db='spider', charset='utf8')
self.cur = self.conn.cursor() def sql_filter(self,sql, max_length=20):
dirty_stuff = ["\"", "\\", "/", "*", "'", "=", "-", "#", ";", "<", ">", "+", "%", "$", "(", ")", "%", "@", "!"]
for stuff in dirty_stuff:
sql = sql.replace(stuff, "")
return sql[:max_length] def get_child_data(self,parent_id, total_pages):
int(parent_id) for page in range(1, total_pages + 1):
#sleep(1)
output = []
print("now_parent_id",parent_id,"now_page:",page)
url = "https://www.zhihu.com/node/TopicsPlazzaListV2"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
}
offset = (page - 1) * 20
data = {'method': 'next', "params": json.dumps({"topic_id": parent_id, "offset": offset, "hash_id": ""})}
response = requests.post(url, data=data, headers=headers)
print(url,response,);
print(data) res = response.json()['msg']
if(len(res) < 0):
break;
for item in res:
html = etree.HTML(item)
title = html.xpath('//img/@alt')[0]
img_url = html.xpath('//img/@src')[0]
topic_url = html.xpath('//a[1]/@href')[0]
topic_id = topic_url.split('/')[-1]
topic_url = urllib.parse.urljoin(url, topic_url)
desc = html.xpath('//p/text()')
if desc is not None and len(desc) == 1:
desc = desc[0]
else:
desc = '' title = self.sql_filter(title, 200)
img_url = self.sql_filter(img_url, 200)
topic_url = self.sql_filter(topic_url, 200)
desc = self.sql_filter(desc, 200) output.append({'title': title, 'img_url': img_url, "topic_url": topic_url, "desc": desc, "topic_id": topic_id,'parent_id': parent_id})
print(output)
self.save_child_topic(output) def save_child_topic(self,data):
for item in data:
import time
# 格式化成2016-03-20 11:45:39形式
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 插入数据
sql = "insert ignore into topic(`title`,`topic_id`,`img_url`,`parent_id`,`desc`,`topic_url`,`level`,`create_time`) values('{}','{}','{}','{}','{}','{}','{}','{}')".format(
item['title'], item['topic_id'], item['img_url'], item['parent_id'], item['desc'], item['topic_url'], 1,
now)
#print(sql)
reCount = self.cur.execute(sql)
self.conn.commit() def __del__(self):
self.cur.close()
self.conn.close()
sql
CREATE TABLE `topic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '' COMMENT '标题',
`topic_id` int(11) NOT NULL,
`img_url` varchar(255) NOT NULL DEFAULT '' COMMENT '子标题图片',
`parent_id` int(11) NOT NULL DEFAULT '0',
`desc` text,
`create_time` varchar(255) NOT NULL DEFAULT '',
`topic_url` varchar(255) DEFAULT '' COMMENT '子标题超链接',
`level` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0父级 ',
PRIMARY KEY (`id`),
UNIQUE KEY `uni_top_par` (`topic_id`,`parent_id`),
KEY `index_parent_id` (`parent_id`),
KEY `index_topic_id` (`topic_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8379 DEFAULT CHARSET=utf8mb4;
requests爬取知乎话题和子话题的更多相关文章
- 爬取知乎热榜标题和连接 (python,requests,xpath)
用python爬取知乎的热榜,获取标题和链接. 环境和方法:ubantu16.04.python3.requests.xpath 1.用浏览器打开知乎,并登录 2.获取cookie和User—Agen ...
- 16、爬取知乎大v张佳玮的文章“标题”、“摘要”、“链接”,并存储到本地文件
爬取知乎大v张佳玮的文章“标题”.“摘要”.“链接”,并存储到本地文件 # 爬取知乎大v张佳玮的文章“标题”.“摘要”.“链接”,并存储到本地文件 # URL https://www.zhihu.co ...
- 教程+资源,python scrapy实战爬取知乎最性感妹子的爆照合集(12G)!
一.出发点: 之前在知乎看到一位大牛(二胖)写的一篇文章:python爬取知乎最受欢迎的妹子(大概题目是这个,具体记不清了),但是这位二胖哥没有给出源码,而我也没用过python,正好顺便学一学,所以 ...
- scrapy 爬取知乎问题、答案 ,并异步写入数据库(mysql)
python版本 python2.7 爬取知乎流程: 一 .分析 在访问知乎首页的时候(https://www.zhihu.com),在没有登录的情况下,会进行重定向到(https://www. ...
- python 爬取知乎图片
先上完整代码 import requests import time import datetime import os import json import uuid from pyquery im ...
- scrapy爬取知乎某个问题下的所有图片
前言: 1.仅仅是想下载图片,别人上传的图片也是没有版权的,下载来可以自己欣赏做手机背景但不商用 2.由于爬虫周期的问题,这个代码写于2019.02.13 1.关于知乎爬虫 网上能访问到的理论上都能爬 ...
- 通过scrapy,从模拟登录开始爬取知乎的问答数据
这篇文章将讲解如何爬取知乎上面的问答数据. 首先,我们需要知道,想要爬取知乎上面的数据,第一步肯定是登录,所以我们先介绍一下模拟登录: 先说一下我的思路: 1.首先我们需要控制登录的入口,重写star ...
- 使用requests爬取梨视频、bilibili视频、汽车之家,bs4遍历文档树、搜索文档树,css选择器
今日内容概要 使用requests爬取梨视频 requests+bs4爬取汽车之家 bs4遍历文档树 bs4搜索文档树 css选择器 内容详细 1.使用requests爬取梨视频 # 模拟发送http ...
- 利用 Scrapy 爬取知乎用户信息
思路:通过获取知乎某个大V的关注列表和被关注列表,查看该大V和其关注用户和被关注用户的详细信息,然后通过层层递归调用,实现获取关注用户和被关注用户的关注列表和被关注列表,最终实现获取大量用户信息. 一 ...
随机推荐
- Linux下开发python django程序(Cookie读写)
1.设置cookie信息(登陆成功后设置登陆用户名,有效期1小时) def login(req): if req.method == 'POST': loginform = LoginForm(req ...
- 关于DFS与BFS
DFS(深度优先搜索) 为无向图 DFS的过程类似于树的先序遍历. 请看图: DFS此图的过程为: 1.首先任意找一个未被便利过的顶点,例如从V1开始,由于率先访问了它,所以需要标记V1即已经访问 ...
- 洛咕 P3964 [TJOI2013]松鼠聚会
有个结论就是把坐标\((x,y)\)变形成\(((x+y)/2,(x-y)/2)\),切比雪夫距离就变成了曼哈顿距离. 所以变换一下坐标直接统计答案即可. // luogu-judger-enable ...
- Lookup 转换组件
查找转换(Lookup)组件用于实现两个数据源的连接,实现的方式是嵌套循环.查找转换通常在内存中缓存查找数据集,然后在输入管道中,把输入数据的每一行都和缓存中的查找数据集进行比较,并输出匹配成功和失败 ...
- CSS快速入门-浮动(float)
一.float概述 浮动(float)是CSS布局常用的一个属性.它可以左右移动,直至它的外边缘碰到包含框或另一个浮动框的外边框. float被设计出来的初衷是用于文字环绕效果.如下代码: <! ...
- 【日常训练】Help Chef Gerasim(Codeforces 99B)
题意与分析 需要注意非法情况.换言之,合法情况其实很苛刻. 代码 /* * ACM Code => cf99b.java * Written by Sam X * Date: 三月, 19, 2 ...
- 宏基4752g 开机进度条卡到75%左右,解决办法
起因:更新win10推送的更新补丁,失败自动回退.开机进度条只能走到75%,bios进不去,最后就卡在开机的logo.(还有其他人是win7直接升级win10,也出现了这种情况.)解决办法:重刷bio ...
- TensorFlow Python2.7环境下的源码编译(二)安装配置
源代码树的根目录中包含了一个名为 configure 的 bash 脚本. $ ./configure 接下来,配置系统会给出各种询问,以确认编译时的配置参数. 一.重要参数解释 Do you w ...
- [硬件配置]Ubuntu 16.04下使用NETGEAR Nighthawk AC1900 (A7000) WIFi USB适配器
为了增强无人机与地面站之间的传输信号,组里买了这款WiFi信号接收器,无奈只有Windows和Mac OS版本的驱动程序.后来不知道从哪里得来的一个偏方可以安装Ubuntu下的驱动,特此记录. 内核降 ...
- Linux命令的那些事(三)
回顾linux命令那些事,前面大致总结了常用的Linux命令 回顾Linux命令那些事(一) clear/mkdir/rmdir/ls/rm/pwd/cd/touch/tree/man/--help ...