需求描述:爬取知乎的答案,爬取并下载一个问题下所有回答中的图片。 实现平台:开发工具PyCharm2017,语言版本Python3。6,Chrome谷歌浏览器。 基本原理:1。发送请求,获取网页HTML源码;解析HTML,获取数据;保存数据。2 模拟浏览器登录,获取并解析HTML,获取数据。利用Python中的库即可便捷实现。 功能实现1:知乎答案爬取 实现思路: 1。首先实现安装好第三方模块requests和bs4并调用。 2。其次设置Http请求头,利用requests访问网页获取到源代码,利用bs模块中的BeautifulSoup得到解析过后的html。 3。随后,分别通过对照网页源代码中标签内容进行匹配,分别获取问题标题、问题内容、点赞数以及答案等内容。 4。最后进行包括知乎答案等信息的打印。 分别对应上述思路进行代码编写。 1。调用第三方模块。 coding:UTF8 爬取知乎答案 importrequests frombs4importBeautifulSoup 2。设置Http请求头:可以在Chrome谷歌浏览器的网页中的任意地方按下F12,打开chrome自带的调试工具,在调试工具中选择network标签,F5刷新网页后在左边找到该网页url,点击该url,选择Headers,就可以看到当前网页的Http头。复制到header{}中。 获取源代码并解析:利用requests和BeautifulSoup实现,并返回解析后的body。 获取网页body里的内容 defgetcontent(url,dataNone): 设置Http请求头,根据自己电脑查一下 header{ Accept:texthtml,applicationxhtmlxml,q0。9,imagewebp,;q0。8, AcceptEncoding:gzip,deflate,sdch, AcceptLanguage:zhCN,q0。8, Connection:keepalive, UserAgent:Mozilla5。0(WindowsNT6。3;WOW64)AppleWebKit537。36(KHTML,likeGecko)Chrome43。0。235 } reqrequests。get(url,headersheader) req。encodingutf8 bsBeautifulSoup(req。text,html。parser)创建BeautifulSoup对象 bodybs。body returnbody 3。标签内容进行class匹配:问题标题QuestionHeadertitle,问题内容RichTextztext,点赞量ButtonVoteButtonVoteButtonup,问题回答ContentItemtime。 获取问题标题 defgettitle(htmltext): datahtmltext。find(h1,{class:QuestionHeadertitle})匹配标签 returndata。string。encode(utf8) 获取问题内容 defgetquestioncontent(htmltext): datahtmltext。find(span,{class:RichTextztext}) print(data。string) ifdata。stringisNone: out fordatastringindata。strings: datastringdatastring。encode(utf8) outoutdatastring。encode(utf8) print(内容:out) else: print(内容:data。string。encode(utf8)) 获取点赞数 defgetansweragree(body): agreebody。find(button,{class:ButtonVoteButtonVoteButtonup}) agreehtmlBeautifulSoup(str(agree),html。parser) allbuttonsagreehtml。findall(button,{class:ButtonVoteButtonVoteButtonup}) onebuttonallbuttons〔0〕 agreenumberonebutton〔arialabel〕 print(agreenumber) 获取答案 defgetresponse(htmltext): out1 responsehtmltext。findall(p,{class:ContentItemtime}) forindexinrange(len(response)): 获取标签 answerhrefresponse〔index〕。find(a,{target:blank}) ifnot(answerhref〔href〕。startswith(javascript)): urlhttp:answerhref〔href〕 bodygetcontent(url) getansweragree(body) answerbody。find(span,{class:RichTextztextCopyrightRichTextrichTextcsshnrfcf}) ifanswer。stringisNone: out fordatastringinanswer。strings: datastringdatastring。encode(utf8) outoutstr(datastring,encodingutf8) else: print(answer。string。encode(utf8)) out1out1out returnurlout1 4。结果输出打印:以一个网址为例,调用之前编写的函数,进行信息的获取和打印。 输入要爬取的网址 URLtargethttps:www。zhihu。comquestion505503990answer2276487889 htmltextgetcontent(URLtarget) titlegettitle(htmltext) print(标题:str(title,encodingutf8)) datagetresponse(htmltext) 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。comlfrip10542797。html 我的Chrome版本是:94。0。4606。71(正式版本)(64位),对应文件夹应该放在 C:ProgramFilesGoogleChromeApplication 2。分别对应上述思路进行代码编写,安装好模块并调用。 爬取知乎问题下的所有图片 fromseleniumimportwebdriver importtime importurllib。request frombs4importBeautifulSoup importhtml。parser 3。自动化打开浏览器并扫码登录知乎,并解析网页HTML信息,查找所有的noscript标签。 defmain(): 确保文件夹中有chromedriver。exe,有的在C:ProgramFilesx86 chromedriverC:ProgramFilesGoogleChromeApplicationchromedriver。exe driverwebdriver。Chrome(chromedriver) time。sleep(5) driver。get(https:www。zhihu。comquestion287084175)打开想要爬取的知乎页面 time。sleep(5) 模拟用户操作 defexecutetimes(times): foriinrange(times): driver。executescript(window。scrollTo(0,document。body。scrollHeight);) time。sleep(3) try: driver。findelementbycssselector(button。QuestionMainAction)。click() print(pagestr(i)) time。sleep(1) except: break 执行次数 executetimes(5) 原网页的信息 resultrawdriver。pagesource这是原网页HTML信息 resultsoupBeautifulSoup(resultraw,html。parser)然后将其解析 resultbfresultsoup。prettify()结构化原HTML文件 withopen(D:python安装包PycharmProjectszhihutupianrawresult。txt,w,encodingutf8)asrawresult:存储路径里的文件夹需要事先创建。 rawresult。write(resultbf) rawresult。close() print(爬取回答页面成功!!!) withopen(D:python安装包PycharmProjectszhihutupiannoscriptmeta。txt,wb)asnoscriptmeta: noscriptnodesresultsoup。findall(noscript)找到所有node noscriptinnerall fornoscriptinnoscriptnodes: noscriptinnernoscript。gettext()获取node内部内容 noscriptinnerallnoscriptinner noscriptallhtml。parser。unescape(noscriptinnerall)。encode(utf8)将内部内容转码并存储 noscriptmeta。write(noscriptall) noscriptmeta。close() print(爬取noscript标签成功!!!) 4。查找所有图片并命名下载。 imgsoupBeautifulSoup(noscriptall,html。parser) imgnodesimgsoup。findall(img) withopen(D:python安装包PycharmProjectszhihutupianimgmeta。txt,w)asimgmeta: count0 forimginimgnodes: ifimg。get(src)isnotNone: imgurlimg。get(src) linestr(count)imgurl imgmeta。write(line) urllib。request。urlretrieve(imgurl,D:python安装包PycharmProjectszhihutupianstr(count)。jpg)一个一个下载图片 count1 imgmeta。close() print(图片下载成功) ifnamemain: main() 5。最后进行包括知乎图片的保存。 最后,有相关爬虫需求欢迎通过公众号联系我们。 公众号:320科技工作室