百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Python爬虫-面向知乎的答案提取和图片下载

zhezhongyun 2025-01-01 23:34 40 浏览

需求描述:爬取知乎的答案,爬取并下载一个问题下所有回答中的图片。

实现平台:开发工具PyCharm2017,语言版本Python3.6,Chrome谷歌浏览器。

基本原理:1.发送请求,获取网页HTML源码;解析HTML,获取数据;保存数据。2

模拟浏览器登录,获取并解析HTML,获取数据。利用Python中的库即可便捷实现。


功能实现1:知乎答案爬取

实现思路:

1. 首先实现安装好第三方模块requests和bs4并调用。

2. 其次设置Http请求头,利用requests访问网页获取到源代码,利用bs模块中的BeautifulSoup得到解析过后的html。

3. 随后,分别通过对照网页源代码中标签内容进行匹配,分别获取问题标题、问题内容、点赞数以及答案等内容。

4. 最后进行包括知乎答案等信息的打印。

分别对应上述思路进行代码编写。

1. 调用第三方模块。

#-*- coding: UTF-8 -*-

# 爬取知乎答案

import requests

from bs4 import BeautifulSoup

2. 设置Http请求头:可以在Chrome谷歌浏览器的网页中的任意地方按下F12,打开chrome自带的调试工具,在调试工具中选择network标签,F5刷新网页后在左边找到该网页url,点击该url,选择Headers,就可以看到当前网页的Http头。复制到header={}中。

获取源代码并解析:利用requests和BeautifulSoup实现,并返回解析后的body。


#获取网页body里的内容

def get_content(url , data = None):

# 设置Http请求头,根据自己电脑查一下

header={

'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',

'Accept-Encoding': 'gzip, deflate, sdch',

'Accept-Language': 'zh-CN,zh;q=0.8',

'Connection': 'keep-alive',

'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'

}


req = requests.get(url, headers=header)

req.encoding = 'utf-8'

bs = BeautifulSoup(req.text, "html.parser") # 创建BeautifulSoup对象

body = bs.body #


return body

3. 标签内容进行class匹配:问题标题——QuestionHeader-title,问题内容——RichText ztext,点赞量——Button VoteButton VoteButton—up,问题回答——ContentItem-time。

#获取问题标题

def get_title(html_text):

data = html_text.find('h1', {'class':' QuestionHeader-title '}) #匹配标签

return data.string.encode('utf-8')


#获取问题内容

def get_question_content(html_text):

data = html_text.find('span', {'class': 'RichText ztext'})

print (data.string)

if data.string is None:

out = ''

for datastring in data.strings:

datastring = datastring.encode('utf-8')

out = out + datastring.encode('utf-8')

print ('内容:\n' + out)

else:

print ('内容:\n' + data.string.encode('utf-8'))


#获取点赞数

def get_answer_agree(body):

agree = body.find('button',{'class': 'Button VoteButton VoteButton--up'})

agree_html = BeautifulSoup(str(agree), "html.parser")

all_buttons = agree_html.find_all("button", {"class": "Button VoteButton VoteButton--up"})

one_button = all_buttons[0]

agree_number = one_button["aria-label"]

print(agree_number)


#获取答案

def get_response(html_text):

out1 = ''

response = html_text.find_all('div', {'class': 'ContentItem-time'})

for index in range(len(response)):

#获取标签

answerhref = response[index].find('a', {'target': '_blank'})

if not(answerhref['href'].startswith('javascript')):

url = 'http:' + answerhref['href']

body = get_content(url)

get_answer_agree(body)

answer = body.find('span', {'class': 'RichText ztext CopyrightRichText-richText css-hnrfcf'})

if answer.string is None:

out = ''

for datastring in answer.strings:

datastring = datastring.encode('utf-8')

out = out + '\n' + str(datastring,encoding = 'utf-8')

else:

print (answer.string.encode('utf-8'))

out1 = out1 + '\n' + out

return url + '\n' + out1

4. 结果输出打印:以一个网址为例,调用之前编写的函数,进行信息的获取和打印。

# 输入要爬取的网址

URL_target = 'https://www.zhihu.com/question/505503990/answer/2276487889'

html_text = get_content(URL_target)

title = get_title(html_text)

print ("标题:" + str(title,encoding = 'utf-8') + '\n')

data = get_response(html_text)

print (data)


功能实现2:知乎图片下载

实现思路:

1. 首先实现安装好chromedriver模拟人为登录浏览器,模拟登录网页,中途拿手机扫码登录。

2. 安装好模块selenium、time、urllib.request 、bs4 和html.parser并调用。

3. 利用chromedriver打开浏览器并登录知乎,利用bs模块中的BeautifulSoup得到解析过后的html。

4. 随后,找到照片并进行下载。

5. 保存所有图片。

思路是先模拟登录网页,(中途拿手机扫码登录),然后逐步爬取所有回答。

1.下载对应Chrome版本的chromedriver。

通过chrome://version/查看版本,下载chromedriver后解压安装。详细可以参考这个说明。

selenium 安装与 chromedriver 安装 :https://www.cnblogs.com/lfri/p/10542797.html

我的Chrome版本是:94.0.4606.71(正式版本)(64 位),对应文件夹应该放在

C:\Program Files\Google\Chrome\Application

2.分别对应上述思路进行代码编写,安装好模块并调用。

# 爬取知乎问题下的所有图片 

from selenium import webdriver

import time

import urllib.request

from bs4 import BeautifulSoup

import html.parser

3.自动化打开浏览器并扫码登录知乎,并解析网页 HTML 信息,查找所有的noscript标签。

def main():

# 确保文件夹中有chromedriver.exe,有的在C:\Program Files x86

chromedriver = 'C:\Program Files\Google\Chrome\Application\chromedriver.exe'

driver = webdriver.Chrome(chromedriver)

time.sleep(5)

driver.get("https://www.zhihu.com/question/287084175") # 打开想要爬取的知乎页面

time.sleep(5)


# 模拟用户操作

def execute_times(times):

for i in range(times):

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

time.sleep(3)

try:

driver.find_element_by_css_selector('button.QuestionMainAction').click()

print("page" + str(i))

time.sleep(1)

except:

break


# 执行次数

execute_times(5)

# 原网页的信息

result_raw = driver.page_source # 这是原网页 HTML 信息

result_soup = BeautifulSoup(result_raw, 'html.parser')# 然后将其解析

result_bf = result_soup.prettify() # 结构化原 HTML 文件

with open("D:/python安装包/PycharmProjects/zhihutupian/raw_result.txt", 'w',encoding="utf-8") as raw_result: # 存储路径里的文件夹需要事先创建。

raw_result.write(result_bf)

raw_result.close()

print("爬取回答页面成功!!!")


with open("D:/python安装包/PycharmProjects/zhihutupian/noscript_meta.txt", 'wb') as noscript_meta:

noscript_nodes = result_soup.find_all('noscript') # 找到所有<noscript>node

noscript_inner_all = ""

for noscript in noscript_nodes:

noscript_inner = noscript.get_text() # 获取<noscript>node内部内容

noscript_inner_all += noscript_inner + "\n"


noscript_all = html.parser.unescape(noscript_inner_all).encode('utf-8') # 将内部内容转码并存储

noscript_meta.write(noscript_all)


noscript_meta.close()

print("爬取noscript标签成功!!!")

4.查找所有图片并命名下载。

img_soup = BeautifulSoup(noscript_all, 'html.parser')

img_nodes = img_soup.find_all('img')

with open("D:/python安装包/PycharmProjects/zhihutupian/img_meta.txt", 'w') as img_meta:

count = 0

for img in img_nodes:

if img.get('src') is not None:

img_url = img.get('src')


line = str(count) + "\t" + img_url + "\n"

img_meta.write(line)

urllib.request.urlretrieve(img_url, "D:/python安装包/PycharmProjects/zhihutupian/" + str(count) + ".jpg") # 一个一个下载图片

count += 1


img_meta.close()

print("图片下载成功")


if __name__ == '__main__':

main()


5.最后进行包括知乎图片的保存。

最后,有相关爬虫需求欢迎通过公众号联系我们.

公众号: 320科技工作室

相关推荐

「layui」表单验证:验证注册

注册界面手动验证获取短信验证码代码原文<!DOCTYPEhtml><htmllang="zh"><head>&...

Full text: Joint statement between China and Kenya on creating an inspiring example in the all-weather China-Africa community with a shared future for the new era

JointStatementBetweenthePeople'sRepublicofChinaandtheRepublicofKenyaonCreatinganInspi...

国际组织最新岗位信息送给你

国际刑警组织PostingTitleITLogisticsManagerGrade5DutyStationAbidjan,IvoryCoastDeadlineforApplicatio...

【新功能】Spire.PDF 8.12.5 支持设置表单域的可见与隐藏属性

Spire.PDF8.12.5已发布。该版本新增支持设置表单域的可见与隐藏属性、添加自定义的元数据以及给PDF文档的元数据添加新的命名空间。本次更新还增强了PDF到DOCX和图片的转换...

AI curbs show Biden&#39;s rejection of cooperation

AIcurbsshowBiden'srejectionofcooperation:ChinaDailyeditorial-Opinion-Chinadaily.com.cnT...

“煤气灯效应”上热搜,这几种有毒的“情感关系”也要注意了……

近日,“煤气灯效应”(theGaslightEffect)再次进入公众视野并登上热搜,引发网友广泛关注。那么,什么是“煤气灯效应”?以“爱”之名进行情绪控制在心理学中,通过“扭曲受害者眼中的真实”...

Qt编写推流程序/支持webrtc265/从此不用再转码/打开新世界的大门

一、前言在推流领域,尤其是监控行业,现在主流设备基本上都是265格式的视频流,想要在网页上直接显示监控流,之前的方案是,要么转成hls,要么魔改支持265格式的flv,要么265转成264,如果要追求...

写给运维的Nginx秘籍

要说Web服务器、代理服务器和调度服务器层面,目前使用最大的要数Nginx。对于一个运维工程师日常不可避免要和Nginx打交道。为了更好地使用和管理Nginx,本文就给大家介绍几个虫虫日常常用的秘籍。...

突破亚马逊壁垒,Web Unlocker API 助您轻松获取数据

在数据驱动决策的时代,电商平台的海量数据是十足金贵的。然而,像亚马逊这样的巨头为保护自身数据资产,构建了近乎完美的反爬虫防线,比如IP封锁、CAPTCHA验证、浏览器指纹识别,常规爬虫工具在这些防线面...

每日一库之 logrus 日志使用教程

golang日志库golang标准库的日志框架非常简单,仅仅提供了print,panic和fatal三个函数对于更精细的日志级别、日志文件分割以及日志分发等方面并没有提供支持.所以催生了很多第三方...

对比测评:为什么AI编程工具需要 Rules 能力?

通义灵码ProjectRules在开始体验通义灵码ProjectRules之前,我们先来简单了解一下什么是通义灵码ProjectRules?大家都知道,在使用AI代码助手的时候,有时...

python 面向对象编程

Python的面向对象编程(OOP)将数据和操作封装在对象中,以下是深度解析和现代最佳实践:一、核心概念重构1.类与实例的底层机制classRobot:__slots__=['...

Windows系统下常用的Dos命令介绍(一)

DOS是英文DiskOperatingSystem的缩写,意思是“磁盘操作系统”。DOS主要是一种面向磁盘的系统软件,说得简单些,DOS就是人给机器下达命令的集合,是存储在操作系统中的命令集。主要...

使用 Flask-Admin 快速开发博客后台管理系统:关键要点解析

一、为什么选择Flask-Admin?Flask-Admin是Flask生态中高效的后台管理框架,核心优势在于:-零代码生成CRUD界面:基于数据库模型自动生成增删改查功能-高度可定制...

Redis淘汰策略导致数据丢失?

想象一下,你的Redis服务器是一个合租宿舍,内存就是床位。当新数据(新室友)要住进来,但床位已满时,你作为宿管(淘汰策略)必须决定:让谁卷铺盖走人?Redis提供了8种"劝退"方案,...