最近晚上学习爬虫,首先从基本的开始;

python3 将urllib,urllib2集成到urllib中了, urllib可以对指定的网页进行请求下载,  beautifulsoup 可以从杂乱的html代码中

分离出我们需要的部分;

注:  beautifulsoup 是一种可以从html 或XML文件中提取数据的python库;

实例1:

from urllib import request
from bs4 import BeautifulSoup as bs
import re header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36'
} def download():
"""
模拟浏览器进行访问;
:param url:
:return:
"""
for pageIdx in range(1, 3, 1):
#print(pageIdx)
url = "https://www.cnblogs.com/#p%s" % str(pageIdx)
print(url)
req = request.Request(url, headers=header)
rep = request.urlopen(req).read()
data = rep.decode('utf-8')
print(data)
content = bs(data)
for link in content.find_all('h3'):
content1 = bs(str(link), 'html.parser')
print(content1.a['href'],content1.a.string)
curhtmlcontent = request.urlopen(request.Request(content1.a['href'], headers=header)).read()
#print(curhtmlcontent.decode('utf-8'))
open('%s.html' % content1.a.string, 'w',encoding='utf-8').write(curhtmlcontent.decode('utf-8')) if __name__ == "__main__":
download()

实例2:

# -- coding: utf-8 --
import unittest
import lxml
import requests
from bs4 import BeautifulSoup as bs def school():
for index in range(2, 34, 1):
try:
url="http://gaokao.chsi.com.cn/gkxx/zszcgd/dnzszc/201706/20170615/1611254988-%s.html" % str(index)
r = requests.get(url=url)
soup = bs(r.content, 'lxml')
city = soup.find_all(name="td",attrs={"colspan":"7"})[0].string
fp = open("%s.txt" %(city), "w", encoding="utf-8")
content1 = soup.find_all(name="tr", attrs={"height": "29"})
for content2 in content1:
try:
contentTemp = bs(str(content2), "lxml")
soup_content = contentTemp.find_all(name="td")[1].string
fp.write(soup_content + "\n")
print(soup_content)
except IndexError:
pass
fp.close()
except IndexError:
pass class MyTestCase(unittest.TestCase):
def test_something(self):
school() if __name__ == '__main__':
unittest.main()

BeatifulSoup支持很多HTML解析器(下面是一些主要的):

解析器 使用方法 优势 劣势
Python标准库 BeautifulSoup(markup, “html.parser”) (1)Python的内置标准库(2)执行速度适中(3)文档容错能力强 Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差
lxml HTML解析器 BeautifulSoup(markup, “lxml”) (1)速度快(2)文档容错能力强 需要安装C语言库
lxml XML解析器 BeautifulSoup(markup, [“lxml”, “xml”]) OR BeautifulSoup(markup, “xml”) (1)速度快(2)唯一支持XML的解析器 需要安装C语言库
html5lib BeautifulSoup(markup, “html5lib”) (1)最好的容错性(2)以浏览器的方式解析文档(3)生成HTML5格式的文档 (1)速度慢(2)不依赖外部扩展

python3: 爬虫---- urllib, beautifulsoup的更多相关文章

  1. Python3 使用 urllib 编写爬虫

    什么是爬虫 爬虫,也叫蜘蛛(Spider),如果把互联网比喻成一个蜘蛛网,Spider就是一只在网上爬来爬去的蜘蛛.网络爬虫就是根据网页的地址来寻找网页的,也就是URL.举一个简单的例子,我们在浏览器 ...

  2. 常见的爬虫分析库(1)-Python3中Urllib库基本使用

    原文来自:https://www.cnblogs.com/0bug/p/8893677.html 什么是Urllib? Python内置的HTTP请求库 urllib.request          ...

  3. urllib+BeautifulSoup无登录模式爬取豆瓣电影Top250

    对于简单的爬虫任务,尤其对于初学者,urllib+BeautifulSoup足以满足大部分的任务. 1.urllib是Python3自带的库,不需要安装,但是BeautifulSoup却是需要安装的. ...

  4. python3爬虫系列19之反爬随机 User-Agent 和 ip代理池的使用

    站长资讯平台:python3爬虫系列19之随机User-Agent 和ip代理池的使用我们前面几篇讲了爬虫增速多进程,进程池的用法之类的,爬虫速度加快呢,也会带来一些坏事. 1. 前言比如随着我们爬虫 ...

  5. python爬虫 - Urllib库及cookie的使用

    http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...

  6. 对于python爬虫urllib库的一些理解(抽空更新)

    urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据. urlopen函数: 在Python3的urllib库中,所有和网 ...

  7. python3爬虫中文乱码之请求头‘Accept-Encoding’:br 的问题

    当用python3做爬虫的时候,一些网站为了防爬虫会设置一些检查机制,这时我们就需要添加请求头,伪装成浏览器正常访问. header的内容在浏览器的开发者工具中便可看到,将这些信息添加到我们的爬虫代码 ...

  8. Python3中Urllib库基本使用

    什么是Urllib? Python内置的HTTP请求库 urllib.request          请求模块 urllib.error              异常处理模块 urllib.par ...

  9. Python3.x:BeautifulSoup()解决中文乱码问题

    Python3.x:BeautifulSoup()解决中文乱码问题 问题: BeautifulSoup获取网页内容,中文显示乱码: 解决方案: 遇到情况也是比较奇葩,利用chardet获取网页编码,然 ...

随机推荐

  1. 排列组合n选m算法

    找10组合算法,非递归 http://blog.csdn.net/sdhongjun/article/details/51475302

  2. 开始一个简单的ASP.NET Web API 2 (C#)

    创建一个Web API 项目 在本教程中,你将使用ASP.NET Web API 来创建一个web API 并返回产品列表. 网页前端使用jQuery 显示结果. 选择ASP.NET Web Appl ...

  3. codeforces472C

    Design Tutorial: Make It Nondeterministic CodeForces - 472C A way to make a new task is to make it n ...

  4. codeforces611C

    New Year and Domino CodeForces - 611C 他们说:“每一年都像多米诺骨牌,一个接一个地倒下去”.但是,一年能够像多米诺骨牌那样放在网格中吗?我不这么认为. Zydsg ...

  5. DRF 版本 认证

    DRF的版本 版本控制是做什么用的, 我们为什么要用 首先我们要知道我们的版本是干嘛用的呢大家都知道我们开发项目是有多个版本的 当我们项目越来越更新~版本就越来越多我们不可能新的版本出了~以前旧的版本 ...

  6. Android路径之Javascript基础-笔记

    一.Javascript概述(知道) a.一种基于对象和事件驱动的脚本语言 b.作用: 给页面添加动态效果 c.历史: 原名叫做livescript.W3c组织开发的标准叫ECMAscipt. d.特 ...

  7. MT【296】必要性探路

    已知$a,b\in R.f(x)=e^x-ax+b$,若$f(x)\ge1$恒成立,则$\dfrac{b-a}{a}$的取值范围_____ 提示:答案:$[-1,\infty)$取$x=0,b\ge0 ...

  8. Hdoj 2045.不容易系列之(3)—— LELE的RPG难题 题解

    Problem Description 人称"AC女之杀手"的超级偶像LELE最近忽然玩起了深沉,这可急坏了众多"Cole"(LELE的粉丝,即"可乐 ...

  9. 自学Python之路-Python网络编程

    自学Python之路-Python网络编程 自学Python之路[第一回]:1.11.2 1.3

  10. 【CF850E】Random Elections(FWT)

    [CF850E]Random Elections(FWT) 题面 洛谷 CF 题解 看懂题就是一眼题了... 显然三个人是等价的,所以只需要考虑一个人赢了另外两个人就好了. 那么在赢另外两个人的过程中 ...