首页/文章/ 详情

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

1年前浏览936

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

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

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

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


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

实现思路:

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

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头。copyheader={}中。

获取源代码并解析:利用requestsBeautifulSoup实现,并返回解析后的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

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

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

#获取问题标题

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)

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


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

实现思路:

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

2. 安装好模块seleniumtimeurllib.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.最后进行包括知图片保存

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

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

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

公zhong号: 320科技工作室

python
著作权归作者所有,欢迎分享,未经许可,不得转载
首次发布时间:2023-01-31
最近编辑:1年前
320科技工作室
硕士 | 结构工程师 lammps/ms/vasp/
获赞 218粉丝 324文章 290课程 0
点赞
收藏
未登录
还没有评论
课程
培训
服务
行家
VIP会员 学习 福利任务 兑换礼品
下载APP
联系我们
帮助与反馈