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

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

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

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

实现平台:开发工具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科技工作室

相关推荐

perl基础——循环控制_principle循环

在编程中,我们往往需要进行不同情况的判断,选择,重复操作。这些时候我们需要对简单语句来添加循环控制变量或者命令。if/unless我们需要在满足特定条件下再执行的语句,可以通过if/unle...

CHAPTER 2 The Antechamber of M de Treville 第二章 特雷维尔先生的前厅

CHAPTER1TheThreePresentsofD'ArtagnantheElderCHAPTER2TheAntechamber...

CHAPTER 5 The King&#39;S Musketeers and the Cardinal&#39;S Guards 第五章 国王的火枪手和红衣主教的卫士

CHAPTER3TheAudienceCHAPTER5TheKing'SMusketeersandtheCardinal'SGuard...

CHAPTER 3 The Audience 第三章 接见

CHAPTER3TheAudienceCHAPTER3TheAudience第三章接见M.DeTrévillewasatt...

别搞印象流!数据说明谁才是外线防守第一人!

来源:Reddit译者:@assholeeric编辑:伯伦WhoarethebestperimeterdefendersintheNBA?Here'sagraphofStea...

V-Day commemorations prove anti-China claims hollow

People'sLiberationArmyhonorguardstakepartinthemilitaryparademarkingthe80thanniversary...

EasyPoi使用_easypoi api

EasyPoi的主要特点:1.设计精巧,使用简单2.接口丰富,扩展简单3.默认值多,writelessdomore4.springmvc支持,web导出可以简单明了使用1.easypoi...

关于Oracle数据库12c 新特性总结_oracle数据库12514

概述今天主要简单介绍一下Oracle12c的一些新特性,仅供参考。参考:http://docs.oracle.com/database/121/NEWFT/chapter12102.htm#NEWFT...

【开发者成长】JAVA 线上故障排查完整套路!

线上故障主要会包括CPU、磁盘、内存以及网络问题,而大多数故障可能会包含不止一个层面的问题,所以进行排查时候尽量四个方面依次排查一遍。同时例如jstack、jmap等工具也是不囿于一个方面的问题...

使用 Python 向多个地址发送电子邮件

在本文中,我们将演示如何使用Python编程语言向使用不同电子邮件地址的不同收件人发送电子邮件。具体来说,我们将向许多不同的人发送电子邮件。使用Python向多个地址发送电子邮件Python...

提高工作效率的--Linux常用命令,能够决解95%以上的问题

点击上方关注,第一时间接受干货转发,点赞,收藏,不如一次关注评论区第一条注意查看回复:Linux命令获取linux常用命令大全pdf+Linux命令行大全pdf为什么要学习Linux命令?1、因为Li...

linux常用系统命令_linux操作系统常用命令

系统信息arch显示机器的处理器架构dmidecode-q显示硬件系统部件-(SMBIOS/DMI)hdparm-i/dev/hda罗列一个磁盘的架构特性hdparm-tT/dev/s...

小白入门必知必会-PostgreSQL-15.2源码编译安装

一PostgreSQL编译安装1.1下载源码包在PostgreSQL官方主页https://www.postgresql.org/ftp/source/下载区选择所需格式的源码包下载。cd/we...

Linux操作系统之常用命令_linux系统常用命令详解

Linux操作系统一、常用命令1.系统(1)系统信息arch显示机器的处理器架构uname-m显示机器的处理器架构uname-r显示正在使用的内核版本dmidecode-q显示硬件系...

linux网络命名空间简介_linux 网络相关命令

此篇会以例子的方式介绍下linux网络命名空间。此例中会创建两个networknamespace:nsa、nsb,一个网桥bridge0,nsa、nsb中添加网络设备veth,网络设备间...