python糗事百科爬虫
来源:互联网 发布:增值税算法公式 编辑:程序博客网 时间:2024/05/16 17:35
思路
1.获取主页源码
#怎么知道网站禁止爬虫#1.想要的内容跟请求道德内容不一样
#2.无法获取到内容,请求失败
#3.点击右键,看不到内容
#怎么解决网站禁止爬虫
#1.伪装浏览器,模拟 加上headers头部信息
#2.告诉网站,我想在用浏览器在访问,而不是用脚本
2.获取文章内容
find_all 找到下面所有标签的内容find 找到一个
'qiushi_tag_119540416'.split('_')[-1] 可以用split分割符
a = 'qiushi_tag_119540416'
a[11:-1] 可以用切片
get_text 获取文字
3.获取评论
4.用户输入操作
代码
import urllib.requestfrom bs4 import BeautifulSoup #导入 bs4 库#Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据#获取主页源码def getContentOrComment(Url): user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/51.0.2704.63 Safari/537.36' headers = {'User-Agent':user_agent}#浏览器信息 req = urllib.request.Request(url = Url,headers = headers) response = urllib.request.urlopen(req) content = response.read() #print(content) return(content)articalUrl = "https://www.qiushibaike.com/textnew/page/%d"#%d占位符commentUrl = "https://www.qiushibaike.com/article/%s" #%s占位符page = 0while True: raw = input("点击enter查看或者输入exit退出,请输入你的选择:") if raw =="exit": break page+=1 Url = articalUrl % page #%代表的是数字 字符串格式化 print(Url) articlePage = getContentOrComment(Url) #获取文章内容 #创建 beautifulsoup 对象 soupArticle = BeautifulSoup(articlePage,'html.parser')#解析网页 解析 #第一步是用爬虫把目标网站的页面抓下来 #第二步就是解析该HTML页面,看看里面的内容到底是新闻、图片还是视频 #Python提供了HTMLParser来非常方便地解析HTML articleFloor = 1#楼层 for string in soupArticle.find_all(attrs = "article block untagged mb15"): # 限制了标签为article block untagged mb15 commentId = str(string.get('id'))[11:] print(articleFloor,".",string.find(attrs="content").get_text().strip())#获取文本 articleFloor+=1 #获取评论 commentPage = getContentOrComment(commentUrl % commentId)#获取详情页的源码 if commentPage is None: continue soupComment = BeautifulSoup(commentPage,'html.parser') commentFloor = 1 for comment in soupComment.find_all(attrs="body"): print(" ",commentFloor,"楼回复:",comment.get_text().strip()) commentFloor += 1
参考
http://www.cnblogs.com/sunnywss/p/6644542.html
http://www.cnblogs.com/hearzeus/p/5151449.html
阅读全文
0 0
- python爬虫糗事百科
- Python糗事百科爬虫
- python爬虫“糗事百科”
- python爬虫糗事百科
- python糗事百科爬虫
- python糗事百科爬虫
- python爬虫(1):糗事百科
- Python爬虫实战:糗事百科
- python爬虫_糗事百科
- 使用python写糗事百科的爬虫
- Python网络爬虫抓取糗事百科
- python爬虫爬取糗事百科
- python 爬虫 爬取糗事百科段子
- Python 爬虫实战 - 糗事百科段子
- Python爬虫学习1--糗事百科
- Python爬虫实战之爬糗事百科
- Python 爬虫 糗事百科 (改)
- Python爬虫 爬取糗事百科段子
- android中通过文件 SharedPreferences Sqlite ContentProvider存储数据
- HGDB修改数据库用户访问权限举例
- 关于socket通信的一点认识
- 向Eclipse Neon中添加Tomcat服务器
- HDU 2079 多重背包组合计数
- python糗事百科爬虫
- Oracle只读表
- Java开发练习1 求一个n阶方阵对角线元素之和。
- CS231n (winter 2016) : Assignment1
- IntentService has no default constructor
- C#+AE 实现点击查询属性功能
- 我们来说说网页弹窗问题alert
- mybatis学习之路----批量更新数据两种方法效率对比
- golang之下划线(_)之语义说明