一、通过Requests模块获取网页内容并使用BeautifulSoup进行解析

这是Python爬虫系列文章第一篇

首先列一下爬虫的四个基本步骤

1.获取数据
2.解析数据
3.提取数据
4.存储数据

下面从最基本的获取数据开始讲起

1、获取内容

import requests
response = requests.get('url')
# requests.get是在调用requests库中的get()方法,它向服务器发送了一个请求,
# 括号里的参数是你需要的数据所在的网址,然后服务器对请求作出了响应。
# 我们把这个响应返回的结果赋值在变量res上。

response的常用属性:

属性 作用
response.status_code 检查请求是否成功
response.content 把response对象转换为二进制数据
response.text 把response对象转换为字符串数据
response.encoding 定义response对象的编码

example图片下载

import requests
res = resuqests.get('https://avatar.csdn.net/3/C/B/3_liusuxilinyue.jpg')
#上面的url就是我的博客的头像
file = open('photo.jpg','wb')
file.write(res.content)
file.close

2、使用BeautifulSoup解析数据和提取数据

BeautifulSoup需要进行安装,因为不是python自带的,pip install BeautifulSoup4
基本解析方式		bs = BeautifulSoup(要解析的字符串文本,'解析器')

解析数据

import requests
from bs4 import BeautifulSoup
res = requests.get('url')
html = res.text
bs = BeautifulSoup(html,'html.parser')

提取数据

方法 作用 用法 示例
find() 提取满足要求的首个数据 BS对象.find(标签,属性) soup.find(‘div’,class_=‘books’)
find_all() 提取满足要求的所有数据 BS对象.find_all(标签,属性) soup.find_all(‘div’,class_=‘books’)

这样提取出来还是tag对象,需要进一步提取

Tag对象的三种常用属性和方法

属性/方法 作用
Tag.find()/Tag.find_all() 提取tag中的tag,与bs对象一样
Tag.text 提取Tag中的文字
Tag[‘属性名’] 提取Tag中某个属性的属性值

上面整个可以归纳为以下图片形式

一、通过Requests模块获取网页内容并使用BeautifulSoup进行解析_第1张图片

Example

import requests
# 引用requests库
from bs4 import BeautifulSoup
# 引用BeautifulSoup库

res_foods = requests.get('http://www.xiachufang.com/explore/')
# 获取数据
bs_foods = BeautifulSoup(res_foods.text,'html.parser')
# 解析数据

tag_name = bs_foods.find_all('p',class_='name')
# 查找包含菜名和URL<p>标签
tag_ingredients = bs_foods.find_all('p',class_='ing ellipsis')
# 查找包含食材的<p>标签
list_all = []
# 创建一个空列表,用于存储信息
for x in range(len(tag_name)):
# 启动一个循环,次数等于菜名的数量
    list_food = [tag_name[x].text[18:-14],tag_name[x].find('a')['href'],tag_ingredients[x].text[1:-1]]
    # 提取信息,封装为列表。注意此处[18:-14]切片和之前不同,是因为此处使用的是<p>标签,而之前是<a>
    list_all.append(list_food)
    # 将信息添加进list_all
print(list_all)
# 打印

这篇文章先写到这,其实这时简单的静态网页已经可以爬取下来了,只是还需要进行存储操作,这里存储放到下一篇进行讲解。

你可能感兴趣的:(Python爬虫)