码迷,mamicode.com
首页 > 编程语言 > 详细

Python知乎热门话题数据的爬取实战

时间:2018-08-10 23:02:46      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:class   query   有一个   源码   .text   模拟   win64   css   web   


import requests
from pyquery import PyQuery as pq

url = ‘https://www.zhihu.com/explore‘
headers = {
‘user-agent‘:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}

# 为了让网页能模拟浏览器的操作来设置一个headers获取网页源码
html = requests.get(url, headers=headers).text

# 初始化,使用pyQuery来把html放到解析库里进行解析
doc = pq(html)
# 进行pyquery解析(里面放的是css选择器参数)对class里有两个参数来进行解析
items = doc(‘.explore-feed.feed-item‘).items()

# 循环遍历筛选后的数据
for item in items:
# 提取里面的问题
question = item.find(‘h2‘).text()
# 提取里面的作者
author = item.find(‘.author-link-line‘).text()
# 提取里面的回复的内容,这里注意一下,在内容的上面有一个textarea被hidden了
answer = pq(item.find(‘.content‘).html()).text()
# 方法一
# 文件的存储以txt文本存储
file = open(‘explore.txt‘, ‘a‘, encoding=‘utf-8‘)
# 文件的写入
file.write(‘\n‘.join([question, author, answer]))
# 每一个内容用特殊符号隔开
file.write(‘\n‘ + ‘=‘ * 50 + ‘\n‘)
# 文件的关闭
file.close()
# 方式二
# 简写的方法这样可以不用去关闭文件,系统已经封装好了关闭的方法
with open(‘explore.txt‘, ‘a‘, encoding=‘utf-8‘) as file:
file.write(‘\n‘.join([question, author, answer]))
file.write(‘\n‘ + ‘=‘ * 50 + ‘\n‘)

Python知乎热门话题数据的爬取实战

标签:class   query   有一个   源码   .text   模拟   win64   css   web   

原文地址:https://www.cnblogs.com/yunlongaimeng/p/9457424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!