python爬取知乎回答

1. 安装库

htmlparser用来解析html。

Beautiful Soup 是一个可以从 HTML 或 XML 文件中提取数据的 Python 库。

pip install beautifulsoup4

Selenium 是浏览器自动化测试框架,使用它来模拟用户操作。

利用 pip 安装 selenium

pip install -U selenium

2. 模拟用户进行滚动和点击操作

使用JS控制滚动条的位置:

window.scrollTo(x,y);

竖向滚动条置底

 window.scrollTo(0,document.body.scrollHeight)
 time.sleep(2)

向下滑动后延迟两毫秒等待页面加载。

在页面上通过审查,找到查看更多回答的html代码

<button class="Button QuestionMainAction"
type="button">查看更多回答</button>

通过

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

来选中并点击这个按钮。

3. html文件结构化

将html文件结构化并保存,原页面的html解析并存储下来

通过prettify()将html结构化,之后存储在本地的txt文件中。

4. 保存并下载图片

注意我们的目的,就是爬取回答下的图片,其他的都不需要。

还是右键审查,可以发现每张图片上面都有的node,没错,这里面存有图片的高清URL和缩略图URL。

每个元素都被html entity编码了,所以我们要将其解码如下。

html.parser.unescape

之后就可以将图片URL保存下来。

最后下载图片。

urllib.request.urlretrieve

5. 结果展示

这里写图片描述

这里写图片描述

这里写图片描述

6. 代码

from selenium import webdriver
import time

import urllib.request

from bs4 import BeautifulSoup

import html.parser

def main():
    driver = webdriver.Chrome()  # 打开浏览器
    driver.get("https://www.zhihu.com/question/40273344") # 打开想要爬取的知乎页面 

    # 模拟用户操作
    def execute_times(times):

        for i in range(times):
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(2)
            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("./output/rawfile/raw_result.txt", 'w',encoding="utf-8") as girls:  # 存储路径里的文件夹需要事先创建。
        girls.write(result_bf)
    girls.close()
    print("爬取回答页面成功!!!")


    with open("./output/rawfile/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标签成功!!!")

    img_soup = BeautifulSoup(noscript_all, 'html.parser')
    img_nodes = img_soup.find_all('img')
    with open("./output/rawfile/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, "./output/image/" + str(count) + ".jpg")  # 一个一个下载图片
                count += 1

    img_meta.close()
    print("图片下载成功")
if __name__ == '__main__':
    main()

转载于:https://www.cnblogs.com/pjc20/p/7707646.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值