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

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. ES6函数增强

    函数参数可以拥有默认值.调用函数时,如果没有进行相应的实参传递,参数就会使用默认值.怎么给参数提供默认值呢?很简单,声明函数时候,给形参赋一个值就可以了,这个值就是参数的默认值. // num2拥有默 ...

  2. git 强制推送

    Git 强制推送方法(一般不建议使用) $ git push -u origin master -f

  3. LIRE图片识别搜索demo--Ubuntu开发

    Ubuntu安装shadowsocks客户端/服务端教程 1.安装shadowsocks sudo apt-get update sudo apt-get install python-pip sud ...

  4. mysql 测试php连接问题

    <?php$servername = "shuhua.dbhost";$username = "shuhua_user";$password = &quo ...

  5. 基准对象object中的基础类型----字典 (六)

    object有如下子类: CLASSES object basestring str unicode buffer bytearray classmethod complex dict enumera ...

  6. PHP 公共方法分享180628

    查看php 类的详情:方法.常量.属性( type(new \Illuminate\Http\Request());) /** * fixme 打印类详情 * @param $class object ...

  7. cf1088C Ehab and a 2-operation task (构造)

    题意:给一个数列,你可以进行至多n+1次操作,每次给一个前缀对某数取模或者加某数,使得最后数列严格单增 考虑到因为是前缀和而且还不能加负数,光靠加是不能让前面的小于后面的 所以要让他先在模某数意义下单 ...

  8. 【redis】redis常用命令及操作记录

    redis-cli是Redis命令行界面,可以向Redis发送命令,并直接从终端读取服务器发送的回复. 它有两种主要模式:一种交互模式,其中有一个REPL(read eval print loop), ...

  9. LVS搭建负载均衡(二)DR模型

    应用场景:LVS配置负载均衡方式之一:dr 测试环境: 配置步骤: 1. 在主机lvs上安装ipvsadm ~]# yum install ipvsadm -y ~]# ipvsadm //启动:该命 ...

  10. webpack入门(五)webpack CLI

    webpack的CLI安装和命令 Installation $ npm install webpack -g The webpack command is now available globally ...