热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python爬取知乎发现文件存储[txt,json,csv,mongodb]

使用XPathimportrequestsimportjsonfromlxmlimportetreefromurllibimportparse遇到不懂的问题?

使用XPath

import requests
import json
from lxml import etree
from urllib import parse
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
url = 'https://www.zhihu.com/explore'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
html = requests.get(url, headers=headers).text
# 响应返回的是字符串,解析为HTML DOM模式 text = etree.HTML(html)
text = etree.HTML(html)
# 返回所有内容的结点位置
node_list = text.xpath('//div[@class="explore-feed feed-item"]')
items ={}
for node in node_list:# xpath返回的列表,这个列表就这一个参数,用索引方式取出来#问题question = node.xpath('.//h2/a')[0].text.replace("\n","")# 作者author = node.xpath('.//*[@class="author-link-line"]/*')[0].text#author = "".join(node.xpath('.//*[@class="author-link-line"]//text()')).replace("\n","")# 回答answer = node.xpath('.//*[@class="content"]')[0].text#answer = "".join(node.xpath('.//*[@class="content"]/text()')).strip()#answer = str(node.xpath('.//*[@class="content"]/text()'))[1:-1]items = {"question" : question,"author" : author,"answer" : answer,} with open("explore.json", "a") as f:#f.write(json.dumps(items, ensure_ascii = False).encode("utf-8") + "\n")f.write(json.dumps(items, ensure_ascii = False) + "\n")

image.png
####保存为TXT

import requests
from lxml import etree
from urllib import parse
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
url = 'https://www.zhihu.com/explore'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
html = requests.get(url, headers=headers).text
# 响应返回的是字符串,解析为HTML DOM模式 text = etree.HTML(html)
text = etree.HTML(html)
# 返回所有内容的结点位置
node_list = text.xpath('//div[@class="explore-feed feed-item"]')for node in node_list:# xpath返回的列表,这个列表就这一个参数,用索引方式取出来#问题question = node.xpath('.//h2/a')[0].text.replace("\n","")# 作者author = node.xpath('.//*[@class="author-link-line"]/*')[0].text#author = "".join(node.xpath('.//*[@class="author-link-line"]//text()')).replace("\n","")# 回答answer = node.xpath('.//*[@class="content"]')[0].text#answer = "".join(node.xpath('.//*[@class="content"]/text()')).strip()#answer = str(node.xpath('.//*[@class="content"]/text()'))[1:-1]with open('explore.txt', 'a', encoding='utf-8') as file:file.write('\n'.join([question, author, answer]))file.write('\n' + '=' * 50 + '\n')

image.png

保存为csv

import requests
from lxml import etree
from urllib import parse
import csvurl = 'https://www.zhihu.com/explore'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
html = requests.get(url, headers=headers).text
# 响应返回的是字符串,解析为HTML DOM模式 text = etree.HTML(html)
text = etree.HTML(html)
# 返回所有内容的结点位置
node_list = text.xpath('//div[@class="explore-feed feed-item"]')for node in node_list:# xpath返回的列表,这个列表就这一个参数,用索引方式取出来#问题question = node.xpath('.//h2/a')[0].text.replace("\n","")# 作者author = node.xpath('.//*[@class="author-link-line"]/*')[0].text#author = "".join(node.xpath('.//*[@class="author-link-line"]//text()')).replace("\n","")# 回答,为方便展示,只取部分内容,text[ :10]answer = node.xpath('.//*[@class="content"]')[0].text[ :10]#answer = node.xpath('.//*[@class="content"]')[0].text#answer = "".join(node.xpath('.//*[@class="content"]/text()')).strip()#answer = str(node.xpath('.//*[@class="content"]/text()'))[1:-1]with open('explore.csv', 'a', encoding='utf-8') as csvfile:fieldnames = ['question', 'author', 'answer']writer = csv.DictWriter(csvfile, fieldnames=fieldnames)writer.writeheader()writer.writerow({'question': question, 'author': author, 'answer': answer})

####读取csv

1 import csv
2
3 with open('explore.csv', 'r', encoding='utf-8') as csvfile:
4 reader = csv.reader(csvfile)
5 for row in reader:
6 print(row)

image
####保存到MongoDB

import requests
from lxml import etree
from urllib import parse
from pymongo import MongoClientclient = MongoClient()
db = client['explore']
collection = db['explore']url = 'https://www.zhihu.com/explore'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
html = requests.get(url, headers=headers).text
# 响应返回的是字符串,解析为HTML DOM模式 text = etree.HTML(html)
text = etree.HTML(html)
# 返回所有内容的结点位置
node_list = text.xpath('//div[@class="explore-feed feed-item"]')for node in node_list:# xpath返回的列表,这个列表就这一个参数,用索引方式取出来#问题question = node.xpath('.//h2/a')[0].text.replace("\n","")# 作者author = node.xpath('.//*[@class="author-link-line"]/*')[0].text#author = "".join(node.xpath('.//*[@class="author-link-line"]//text()')).replace("\n","")# 回答answer = node.xpath('.//*[@class="content"]')[0].text#answer = "".join(node.xpath('.//*[@class="content"]/text()')).strip()#answer = str(node.xpath('.//*[@class="content"]/text()'))[1:-1]items = {"question" : question,"author" : author,"answer" : answer,} if collection.insert(items):print('Saved to Mongo')

image


推荐阅读
  • Python瓦片图下载、合并、绘图、标记的代码示例
    本文提供了Python瓦片图下载、合并、绘图、标记的代码示例,包括下载代码、多线程下载、图像处理等功能。通过参考geoserver,使用PIL、cv2、numpy、gdal、osr等库实现了瓦片图的下载、合并、绘图和标记功能。代码示例详细介绍了各个功能的实现方法,供读者参考使用。 ... [详细]
  • 使用正则表达式爬取36Kr网站首页新闻的操作步骤和代码示例
    本文介绍了使用正则表达式来爬取36Kr网站首页所有新闻的操作步骤和代码示例。通过访问网站、查找关键词、编写代码等步骤,可以获取到网站首页的新闻数据。代码示例使用Python编写,并使用正则表达式来提取所需的数据。详细的操作步骤和代码示例可以参考本文内容。 ... [详细]
  • 文章目录简介HTTP请求过程HTTP状态码含义HTTP头部信息Cookie状态管理HTTP请求方式简介HTTP协议(超文本传输协议)是用于从WWW服务 ... [详细]
  • 本文介绍了响应式页面的概念和实现方式,包括针对不同终端制作特定页面和制作一个页面适应不同终端的显示。分析了两种实现方式的优缺点,提出了选择方案的建议。同时,对于响应式页面的需求和背景进行了讨论,解释了为什么需要响应式页面。 ... [详细]
  • 本文整理了常用的CSS属性及用法,包括背景属性、边框属性、尺寸属性、可伸缩框属性、字体属性和文本属性等,方便开发者查阅和使用。 ... [详细]
  • pyecharts 介绍
    一、pyecharts介绍ECharts,一个使用JavaScript实现的开源可视化库,可以流畅的运行在PC和移动设备上,兼容当前绝大部 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • 本文讨论了Kotlin中扩展函数的一些惯用用法以及其合理性。作者认为在某些情况下,定义扩展函数没有意义,但官方的编码约定支持这种方式。文章还介绍了在类之外定义扩展函数的具体用法,并讨论了避免使用扩展函数的边缘情况。作者提出了对于扩展函数的合理性的质疑,并给出了自己的反驳。最后,文章强调了在编写Kotlin代码时可以自由地使用扩展函数的重要性。 ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • 本文介绍了Windows操作系统的版本及其特点,包括Windows 7系统的6个版本:Starter、Home Basic、Home Premium、Professional、Enterprise、Ultimate。Windows操作系统是微软公司研发的一套操作系统,具有人机操作性优异、支持的应用软件较多、对硬件支持良好等优点。Windows 7 Starter是功能最少的版本,缺乏Aero特效功能,没有64位支持,最初设计不能同时运行三个以上应用程序。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • python限制递归次数(python最大公约数递归)
    本文目录一览:1、python为什么要进行递归限制 ... [详细]
  • SpringBoot整合SpringSecurity+JWT实现单点登录
    SpringBoot整合SpringSecurity+JWT实现单点登录,Go语言社区,Golang程序员人脉社 ... [详细]
  • 本文介绍了NetCore WebAPI开发的探索过程,包括新建项目、运行接口获取数据、跨平台部署等。同时还提供了客户端访问代码示例,包括Post函数、服务器post地址、api参数等。详细讲解了部署模式选择、框架依赖和独立部署的区别,以及在Windows和Linux平台上的部署方法。 ... [详细]
author-avatar
2012我的语言
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有