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和其关注用户和被关注用户的详细信息,然后通过层层递归调用,实现获取关注用户和被关注用户的关注列表和被关注列表,最终实现获取大量用户信息. 一 ...
随机推荐
- SpringMVC初写(三)Controller的生命周期
Spring框架默认创建的对象的方式是单例,所以业务控制器Controller也是一个单例对象 由此可证明,无论是同一次请求还是同一次会话和不同请求它的对象都是相同的 然而由于对象是单例的,随之而来的 ...
- ELK批量删除索引
一.存在问题 用了一段时间elk发现如果索引长时间不删除,elk会越来越慢,重启elasticsearch服务器节点之前同步时间也会很长 二.解决方法(定期删除索引) 1.在elasticsearch ...
- Gitlab+Jenkins学习之路(七)之发布PHP项目
使用git+jenkins实现持续集成 Step1:构建一个自由风格的php-deploy Step2:Gernal配置,丢弃旧的构建,防止jenkins构建较多之后变臃肿 Step3:源码管理:这里 ...
- tornado-About Web
1.轻量级的web开发框架,没有像django那样的命令行工具,只用于写一些小的脚本 (1)安装tornado包 pip intall tornado # conda install tornado( ...
- 关于js中直接获取后台的值,直接弹窗获取到的值
js里获取后台的值,以前我都是后台通过jsp中的<input>EL表达式: 后台代码把传向页面的值放入request:request.setAttribute("Success& ...
- lemon批量蒯
RT,很久以前写的拿出来骗一骗访问量 把sh文件扔进source里面运行sh *.sh 从子目录蒯出来: #!/bin/bash for file in ./*/*/*.cpp do name=${f ...
- mtr语言真是逆天了
实践证明,设计一个语言,还不是简单的解释没一行哦
- jQuery插件编写基础之“又见弹窗”
本文将通过一个实例来引出jQuery插件开发中的一些细节,首先介绍下jQuery插件开发的一些基础知识. jQuery的插件开发主要分为两类: 1. 类级别,即在jQuery类本身上扩展方法,类似与 ...
- 为什么你写的用例测不出Bug来?
我们写测试用例的目的是为了能够整理思路,把要测试的地方列出来,做为知识的积淀,用例可以交给其他测试人员执行,或者是跟需求提出者进行讨论,对用例进行补充和修改.那么为啥你写的用例测不出Bug来呢,真的是 ...
- Python之pexpect详解
一.引子 Pexpect程序主要用于人机对话的模拟,就是那种系统提问,人来回答yes/no,或者账号登陆输入用户名和密码等等的情况.因为这种情况特别多而且繁琐,所以很多语言都有各种自己的实现.最初的第 ...