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

爬虫主要应对的问题: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. js编译原理(你不知道的javascript)

    虽然通常将js归类为"动态"或"解释执行"语言,但其实也可把它看成是一门编译语言.只不过这个所谓的编译与传统的编译语言不同,它不是提前编译的,编译结果也不能在分 ...

  2. 创建Node.js TypeScript后端项目

    1.安装Node.js扩展,支持TypeScript语法 npm install -g typescript   npm install -g typings 2.创建项目目录project_fold ...

  3. const 成员函数

    我们知道,在成员函数中,如果没有修改成员变量,应该给成员函数加上 const 修饰符,例如 #include <iostream> using namespace std; class F ...

  4. RedisHelper帮助类

    using Newtonsoft.Json; using RedLockNet.SERedis; using RedLockNet.SERedis.Configuration; using Stack ...

  5. min-max容斥 hdu 4336 && [BZOJ4036] 按位或

    题解: 之前听说过这个东西但没有学 令$max(S)$表示S中编号最大的元素,$min(S)$表示编号中最小的元素 $$max(S)=\sum{T \in S} {(-1)}^{|T|+1} min( ...

  6. c_数据结构_队的实现

    # 链式存储#include<stdio.h> #include<stdlib.h> #define STACK_INIT_SIZE 100//存储空间初始分配量 #defin ...

  7. Mapreduce的序列化和流量统计程序开发

    一.Hadoop数据序列化的数据类型 Java数据类型 => Hadoop数据类型 int IntWritable float FloatWritable long LongWritable d ...

  8. hdu4791-Alice's Print Service

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4791 题目解释:给你一组数据s1,p1,s2,p2...sn,pn,一个数字q,问你当要打印q张资料时 ...

  9. WIN10 拨号连接下 如何开启移动热点

    错误提示为:我们无法设置移动热点,因为你的电脑未建立以太网,WIFI或手机网络连接. 解决方法: 1. 首先用手机或其他设备建立无线热点.  2. 电脑连接步骤1中的热点,电脑端打开移动热点.  3. ...

  10. Laravel安装redis扩展

    Laravel安装redis扩展 1.使用命令行,执行(当然要先安装composer) composer require predis/predis 2.执行完就安装好了,redis相关配置可以到.e ...