网络爬虫,是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。

爬虫主要应对的问题:1.http请求 2.解析html源码 3.应对反爬机制。

觉得爬虫挺有意思的,恰好看到知乎有人分享的一个爬虫小教程:https://zhuanlan.zhihu.com/p/20410446 立马学起!

主要步骤:

1、按照教程下载python、配置环境变量,学习使用pip命令、安装开发ide:pycharm

2、学习使用python发送请求获取页面

3、使用chrome开发者工具观察页面结构特征,使用beautifulsoup解析页面

4、保存页面到本地文件

遇到的主要问题:

1.python基本语法:变量、函数、循环、异常、条件语句、创建目录、写文件。可以参考《Python基础教程

2.python缩进很重要,缩进决定语句分组和层次,在循环的时候尤其看清楚。

3.编码格式:从代码编辑、到网页内容、中文文件名,无处不有编码格式的问题。可以参考 《Python编码问题整理

4.beautifulsoup使用。可以参考 《Python爬虫利器二之Beautiful Soup的用法

5.抓取规则失效,重新分析失效页面,重新选择页面特征。

实践,用爬虫获取网页上的试题(自动抓取下一页)代码:

# encoding=utf8
#设置编辑源py文件的编码格式为utf8
import requests, sys, chardet, os, time, random, time
from bs4 import BeautifulSoup reload(sys) #必须要重新加载
sys.setdefaultencoding("utf8") print sys.getdefaultencoding(), sys.getfilesystemencoding() # utf8 mbcs:MBCS(Multi-ByteChactacterSystem,即多字节字符系统)它是编码的一种类型,而不是某个特定编码的名称
path = os.getcwd() #获取当前文件所在目录
newPath = os.path.join(path, "Computer")
if not os.path.isdir(newPath):
os.mkdir(newPath) #新建文件夹
destFile = unicode(newPath + "/题目.docx","utf-8) #存为word也可以,不过后续用office编辑后,保存的时候总需要另存为;用unicode()后,文件名取中文名不会变成乱码 #最常见的模拟浏览器,伪装headers
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'
} def downLoadHtml(url):
html = requests.get(url, headers=headers)
content = html.content
contentEn = chardet.detect(content).get("encoding", "utf-8")
# print contentEn #GB2312
try:
tranCon = content.decode(contentEn).encode(sys.getdefaultencoding())#转换网页内容编码格式;消除中文乱码
except Exception:
return content #用了编码转换,为什么还是存在少量页面异常?
# print tranCon
else:
return tranCon def parseHtml(url):
# print url, "now"
content = downLoadHtml(url)
contentEn = chardet.detect(content).get("encoding", "utf-8")
soup = BeautifulSoup(content, "html.parser") # soup.name [document] BeautifulSoup 对象表示的是一个文档的全部内容
# 查找下一页url
theUL = soup.find("ul", {"class": "con_updown"})
theLi = theUL.find("li")
href = theLi.find("a").get("href")
preUrl = None
if href:
print href, "next"
preUrl = href # 查找所需内容
topics = []
try:
divCon = soup.find("div", attrs={"class": "con_nr"})
if divCon:
subjects = divCon.find_all("p") # __len__属性不是整数,而是:method-wrapper '__len__' of ResultSet object
index = 0 #借助index标识查找第几个,还有别的方式?
for res in subjects:
#跳过不想要的导读行内容
if index == 0 and res.string == "【导读】":
index = 1 # 跳出循环也要加1
continue # 跳过 导读
topic = res.string # res有子标签及文本,就会返回None
if topic:
#按需要,只留下纯文本,保存到文件
try:
parsed = topic.decode(contentEn).encode("utf8")
except Exception:
topics.append("本页面解码有误,请自行查看: " + url + "\n") # '%d' %index str(index) 数字转字符串
break
else:
topics.append(parsed + "\n")
index = index + 1
topics.append("\n")
else:
topics.append("本页面查找试题有误,请自行查看: " + url + "\n")
except Exception:
topics.append("本页面解析有误,请自行查看: " + url + "\n") fp = open(destFile, 'a') # a追加写
fp.writelines(topics)
fp.close()
return preUrl #执行.py文件的入口
if __name__ == '__main__':
i = 0 #记录处理了多少页面
next = "http://xxxxx/1.html" #起始页面
print "start time:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) #打印时间,看跑了多久
print next, "start"
while next and i < 1000:
next = parseHtml(next)
i = i + 1
#sTime = random.randint(3, 8) #随机整数 [3,8)
#time.sleep(sTime) # 休息:防反爬
print "end time:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print "i =", i, "url:", next
fp = open(destFile, 'a') # a追加写
fp.writelines(["lastPage:" + str(next) + "\n", "total:" + str(i) + "\n"]) # None及数字:无法和字符串用 + 拼接
fp.close()

抓取博客内容,未完待续……

#encoding=utf8
import sys,requests,chardet
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding("utf8") url = "http://www.cnblogs.com/"
agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"
headers={'User-Agent': agent}
data={'user': '', 'pass': ''}
syscode = sys.getdefaultencoding()
print syscode
titles = []
def getHtml(url):
if url:
response = requests.post(url,headers=headers,data=data)
if response.status_code != 200:
return None
content = response.content
#print content
contentEn = chardet.detect(content).get("encoding", "utf-8")
try:
tranCon = content.decode(contentEn).encode(syscode)
except Exception:
return content
else:
#print tranCon
return tranCon
else:
return None def parseHtml(html):
if html:
soup = BeautifulSoup(html,"html.parser")
tags = soup.find("div",attrs={"class":"catListTag"}).find_all("a")
for tag in tags:
href = tag.get("href")
titles.add(href) def getWords():
strs = ""
if titles.__len__() != 0:
for item in titles:
strs = strs + item;
tags = jieba.analyse.extract_tags(strs,topK=100,withWeight=True)
for item in tags:
print(itme[0] + " " + str(int(item[1]*1000))) if __name__ == '__main__':
html = getHtml(url)
parseHtml(html)
getWords

零python基础--爬虫实践总结的更多相关文章

  1. Python基础+爬虫基础

    Python基础+爬虫基础 一.python的安装: 1.建议安装Anaconda,会自己安装一些Python的类库以及自动的配置环境变量,比较方便. 二.基础介绍 1.什么是命名空间:x=1,1存在 ...

  2. Python基础爬虫

    搭建环境: win10,Python3.6,pycharm,未设虚拟环境 之前写的爬虫并没有架构的思想,且不具备面向对象的特征,现在写一个基础爬虫架构,爬取百度百科,首先介绍一下基础爬虫框架的五大模块 ...

  3. Python 基础爬虫架构

    基础爬虫框架主要包括五大模块,分别为爬虫调度器.url管理器.HTML下载器.HTML解析器.数据存储器. 1:爬虫调度器主要负责统筹其他四个模块的协调工作 2: URL管理器负责管理URL连接,维护 ...

  4. Python基础——爬虫以及简单的数据分析

    目标:使用Python编写爬虫,获取链家青岛站的房产信息,然后对爬取的房产信息进行分析. 环境:win10+python3.8+pycharm Python库: import requests imp ...

  5. python基础爬虫,翻译爬虫,小说爬虫

    基础爬虫: # -*- coding: utf-8 -*- import requests url = 'https://www.baidu.com' # 注释1 headers = { # 注释2 ...

  6. python 基础-爬虫-数据处理,全部方法

    生成时间戳 1. time.time() 输出 1515137389.69163 ===================== 生成格式化的时间字符串 1. time.ctime() 输出 Fri Ja ...

  7. 【python】爬虫实践

    参考链接 https://blog.csdn.net/u012662731/article/details/78537432 详解 python3 urllib https://www.jianshu ...

  8. python基础-爬虫

    爬虫引入 爬虫: 1 百度:搜索引擎 爬虫:spider   种子网站开始爬,下载网页,分析链接,作为待抓取的网页 分词 index:词--->某个结果 Page rank(1 网站很大(互链) ...

  9. 《Python机器学习及实践:从零开始通往Kaggle竞赛之路》

    <Python 机器学习及实践–从零开始通往kaggle竞赛之路>很基础 主要介绍了Scikit-learn,顺带介绍了pandas.numpy.matplotlib.scipy. 本书代 ...

随机推荐

  1. 阿里云各Linux发行版netcore兼容性评估报告---来自大石头的测试

    阿里云各Linux发行版netcore兼容性评估报告---来自大石头的测试 结论:    优先选择CentOS/Ubuntu,可选AliyunLinux(CentOS修改版)              ...

  2. python 通过js控制滚动条拉取全文 通过psutil获取pid窗口句柄,通过win32gui使程序窗口前置 通过autopy实现右键菜单和另存为操作

    1.参考 利用 Python + Selenium 自动化快速截图 利用 Python + Selenium 实现对页面的指定元素截图(可截长图元素) 使用python获取系统所有进程PID以及进程名 ...

  3. Ubuntu16.04 将其他磁盘挂载到 /home, 解决/home空间不足

    本文转载自: https://blog.csdn.net/handsome_for_kill/article/details/52654724 1.查看磁盘信息 sudo fdisk -l 查看分区的 ...

  4. MariaDB配置、集群

    MariaDB在centos 7.3的安装,配置和集群搭配 阿里云最新选配系统中,只有centos7.3可选,因此,基于centos 7的MariaDB的安装,配置... 全部删除MySQL/Mari ...

  5. 动态规划——Best Time to Buy and Sell Stock III

    题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格. 如果最多进行两次交易,但必须在买进一只股票前清空手中的股票,求最大的收益. 示例 1:Input: [3,3,5,0,0,3 ...

  6. STL复习之 map & vector --- disney HDU 2142

    题目链接: https://vjudge.net/problem/40913/origin 大致题意: 这是一道纯模拟题,不多说了. 思路: map模拟,vector辅助 其中用了map的函数: er ...

  7. [POJ2559]Largest Rectangle in a Histogram (栈)

    题意 如图所示,在一条水平线上有n个宽为1的矩形,求包含于这些矩形的最大子矩形面积(图中的阴影部分的面积即所求答案). 思路 一个很老的,也是一个很好的题目. 维护一个单调栈即可. 不过在洛谷SP18 ...

  8. JavaScript(四)

    条件语句 通过条件来控制程序的走向,就需要用到条件语句. 运算符 1.算术运算符: +(加). -(减). *(乘). /(除). %(求余)2.赋值运算符:=. +=. -=. *=. /=. %= ...

  9. ECMA Script 6_模块加载方案 ES6 Module 模块语法_import_export

    1. 模块加载方案 commonJS 背景: 历史上,JavaScript 一直没有模块(module)体系, 无法将一个大程序拆分成互相依赖的小文件,再用简单的方法拼装起来. 其他语言都有这项功能: ...

  10. [LeetCode] Transform to Chessboard 转为棋盘

    An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, or an ...