python爬虫库的常见用法_$python爬虫系列(2)—— requests和BeautifulSoup库的基本用法...

本文介绍Python爬虫的基础知识,涵盖requests库与BeautifulSoup库的安装及使用方法。通过实例演示如何抓取网页内容并解析HTML数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要介绍python爬虫的两大利器:requests和BeautifulSoup库的基本用法。

1. 安装requests和BeautifulSoup库

可以通过3种方式安装:

easy_install

pip

下载源码手动安装

这里只介绍pip安装方式:

pip install requests

pip install BeautifulSoup4

2. requests基本用法示例

# coding:utf-8

import requests

# 下载新浪新闻首页的内容

url = 'http://news.sina.com.cn/china/'

# 用get函数发送GET请求,获取响应

res = requests.get(url)

# 设置响应的编码格式utf-8(默认格式为ISO-8859-1),防止中文出现乱码

res.encoding = 'utf-8'

print type(res)

print res

print res.text

# 输出:

'''

国内新闻_新闻中心_新浪网

...

'''

下面将上面获取到的网页html内容写入到文件中,这里有一点需要注意的是:python是调用ASCII编码解码程序去处理字符流的,当字符不属于ASCII范围时会抛异常(ordinal not in range(128)),所以要提前设置程序的默认编码:

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

然后再将响应的html内容存入文件中:

with open('content.txt','w+') as f:

f.write(res.text)

3. BeautifulSoup基本用法

1. 自定义测试html

html = '''

Hello World

This is link1

This is link2

'''

2. 从html文本中获取soup

from bs4 import BeautifulSoup

# 这里指定解析器为html.parser(python默认的解析器),指定html文档编码为utf-8

soup = BeautifulSoup(html,'html.parser',from_encoding='utf-8')

print type(soup)

# 输出:

3. soup.select()函数用法

(1) 获取指定标签的内容

header = soup.select('h1')

print type(header)

print header

print header[0]

print type(header[0])

print header[0].text

# 输出:

'''

[

Hello World

]

Hello World

Hello World

'''

alinks = soup.select('a')

print [x.text for x in alinks]

# 输出:[u'This is link1', u'This is link2']

(2) 获取指定id的标签的内容(用'#')

title = soup.select('#title')

print type(title)

print title[0].text

# 输出:

'''

Hello World

'''

(3) 获取指定class的标签的内容(用'.')

alinks = soup.select('.link')

print [x.text for x in alinks]

# 输出:[u'This is link1', u'This is link2']

(4) 获取a标签的链接(href属性值)

print alinks[0]['href']

# 输出:#link1

(5) 获取一个标签下的所有子标签的text

body = soup.select('body')[0]

print body.text

# 输出:

'''

Hello World

This is link1

This is link2

'''

(6) 获取不存在的标签

aa = soup.select('aa')

print aa

# 输出:[]

(7) 获取自定义属性值

html2 = 'This is a link.'

soup2 = BeautifulSoup(html2,'html.parser')

alink = soup2.select('a')[0]

print alink['qoo']

print alink['abc']

# 输出:

'''

123

456

'''

4. soup.find()和soup.find_all()函数用法

(1) find()和find_all()函数原型:

find和find_all函数都可根据多个条件从html文本中查找标签对象,只不过find的返回对象类型为bs4.element.Tag,为查找到的第一个满足条件的Tag;而find_all的返回对象为bs4.element.ResultSet(实际上就是Tag列表),这里主要介绍find函数,find_all函数类似。

find(name=None, attrs={}, recursive=True, text=None, **kwargs)

注:其中name、attrs、text的值都支持正则匹配。

find_all(name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)

注:其中name、attrs、text的值都支持正则匹配。

(2) find函数的用法示例

html = '

this is my link

'

soup = BeautifulSoup(html,'html.parser')

a1 = soup.find('a')

print type(a1)

# 输出:

print a1.name

print a1['href']

print a1['class']

print a1.text

# 输出:

'''

a

www.test.com

[u'mylink1', u'mylink2']

this is my link

'''

# 多个条件的正则匹配:

import re

a2 = soup.find(name = re.compile(r'\w+'),class_ = re.compile(r'mylink\d+'),text = re.compile(r'^this.+link$'))

# 注:这里的class属性之所以写成'class_',是为了防止和python关键字class混淆,其他属性名写正常的名就行,不用这样特殊处理

print a2

# 输出:

'''

this is my link

'''

# find函数的链式调用

a3 = soup.find('p').find('a')

print a3

# 输出:

'''

this is my link

'''

# attrs参数的用法

# 注:支持正则匹配属性值(包括自定义属性)

import re

html = '

'

soup = BeautifulSoup(html,'html.parser')

div = soup.find('div',attrs = {'class':'myclass','my-attr':re.compile(r'\d+\w+')})

print div

# 输出:

'''

'''

4. 网络爬虫基本架构

5. 补充

1. 代理访问

有时候为了避免封IP,或者在某些公司内网访问外网时候,需要用到代理服务器发送请求,代理的用法示例:

import requests

proxies = {'http':'http://proxy.test.com:8080','https':'http://proxy.test.com:8080'} # 其中proxy.test.com即为代理服务器的地址

url = 'https://www.baidu.com' # 这个url为要访问的url

resp = requests.get(url,proxies = proxies)

如果代理服务器需要账号、密码,则可以这样写proxies:

proxies = {'http':'http://{username}:{password}@proxy.test.com:8080','https':'http://{username}:{password}@proxy.test.com:8080'}

2. 向https的url发送请求

有时候向https的url发送请求会报错:ImportError:no module named certifi.

解决方法:在发送请求时关闭校验:verify = False,如:

resp = requests.get('https://test.com',verify = False)

注:也可通过在headers中传相关鉴权参数来解决此问题。

3. httpbin.org

httpbin.org是requests库的作者开发的一个网站,可以专门用来测试requests库的各种功能,其页面如下:

但httpbin.org的服务器在国外,访问速度比较慢。所以需要在本地搭建一个该网站的镜像,方法如下:

前提:安装好requests库,才能基于该网站测试requests库的功能。

pip install gunicorn httpbin

gunicorn httpbin:app

浏览器输入:127.0.0.1:8000,即可访问。

注:以上步骤在windows下会报错:缺少模块pwd.fcanl,在linux下没问题。

4. requests库官方文档

随机推荐

js正则匹配只能输入有效数字可加小数点

var reg = /^\d+\.?\d*$/; if(value.search(/^\d+\.?\d*$/)===0 && parseFloat(value)>0){//只能输 ...

iOS 开发之照片框架详解(2)

一. 概况 本文接着 iOS 开发之照片框架详解,侧重介绍在前文中简单介绍过的 PhotoKit 及其与 ALAssetLibrary 的差异,以及如何基于 PhotoKit 与 AlAssetLib ...

Loadrunner基础:Loadrunner Vuser基本概念和应用

学习示例 Loadrunner自带有WebTour的网站可以帮助初学者学习性能测试安装完Loadrunner以后进入到Program Files下的WebTour文件加,启动WebTour服务在浏览器 ...

今天用css做了一个QQ登录页面

...

[swustoj 371] 回文数

回文数(0371) 问题描述 一个自然数如果把所有数字倒过来以后和原来的一样,那么我们称它为回文数.例如151和753357.我们可以把所有回文数从小到大排成一排:1, 2, 3, 4, 5, 6, ...

java中jdk环境配置

配置java环境,俗称jdk环境 首先进入配置环境的目录下:右键鼠标我的电脑->属性->高级系统设置->环境变量,在对应的"系统变量"框下配置一下变量: 规范的配 ...

隐式intent启动电子邮件,不需要非电子邮件应用程序。

Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setType("text/plain"); intent.put ...

Intellij-创建Maven项目速度慢

原因: IDEA根据maven archetype的本质,其实是执行mvn archetype:generate命令,该命令执行时,需要指定一个archetype-catalog.xml文件. 该命令 ...

SpringMvc返回报文形式的控制-验证方法: JSON or HTML or XML

首先,请求通过accept请求头声明了支持的返回格式 然后,框架根据该请求头和代码实现(注解)选择了对应的MessageConverter处理返回! 一.验证过程 1.返回html 1.1.请求组装 ...

laravel学习笔记一

指定端口 数据迁移 php artisan migrate:install 任何路由 match get,post只选择其一 没有表名对应默认的posts表,如果表为post就不行 时区不对时 分页 ...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值