数据分析——Python网络爬虫(四){爬虫库的使用}

爬虫库

爬虫的步骤

获取网页源代码-urllib或者request等 信息提取--正则表达式或者bs或者lmxl等 保存本地数据库

爬虫库的作用就是获取网页源代码,学习之前需要学习数据分析------Python网络爬虫(二){Http基本原理}

urllib库

Python内置的http请求库,包括如下模块:

  • requests:http请求模块,用来模拟发送请求,传入url及额外参数
  • error:异常处理模块,如果出现请求错误,可以捕获异常
  • parse:提供url处理方法,如拆分,解析,合并等
  • robotparse:识别网站的robots.txt文件,判断哪些网站可以爬

发送请求

两种方法

  • urlopen():最基本的构造HTTP请求的方法,模拟浏览器的一个请求 发起过程,可以处理get请求或post请求
  • Request:声明一个request对象,该对象可以包括header等信息, 然后用urlopen打开
python 复制代码
#get请求,访问百度
import urllib.request
response=urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))#decode就是解码后的响应
response.status #响应状态
response.getheaders() #响应头

获取网站源代码后 ,可以得知,网站的响应码,以及网站的响应头

python 复制代码
#post请求
import urllib.parse
import urllib.request
da = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
#urlencode方法将参数字典转换为字符串
response = urllib.request.urlopen('http://httpbin.org/post',data=da)
print(response.read())
python 复制代码
#Request,可以加headers信息
import urllib.request
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
request = urllib.request.Request('http://www.baidu.com',headers=headers)
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

headers详见数据分析------Python网络爬虫(二){Http基本原理}

案例

案例一:提取链家房源图片

python 复制代码
## 获取网页的源代码
url='https://tj.lianjia.com/ditiezufang/li110458004/'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
request = urllib.request.Request(url,headers=headers)
response = urllib.request.urlopen(request)
if response.status==200:   #判断是否正常响应
    html=response.read().decode('utf-8')
## 编写正则表达式
import re
reg='data-src="(.*o_auto|.*\.jpg)"\n'#源代码格式图片
imgre=re.compile(reg)
imglist = imgre.findall(html)
## 保存到本地数据库 
import os
os.makedirs('C:\\Users\\90541\\Desktop\\数据分析\\pycode\\picture')  #指定路径下创建目录
os.chdir('C:\\Users\\90541\\Desktop\\数据分析\\pycode\\picture')# 工作路径指向这个目录
x=1
for img in imglist:
    img=img.replace('250x182','780x439')
    urllib.request.urlretrieve(img,'%s.jpg' % x)#直接将远程数据下载到本地
    x+=1

案例二:豆瓣电影分类排行榜(JSON数据格式)

涉及到爬取多页内容

python 复制代码
# 获取网页的源代码
import urllib
url='https://movie.douban.com/j/chart/top_list?type=25&interval_id=100%3A90&action=&start=0&limit=20'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
request = urllib.request.Request(url,headers=headers)
response = urllib.request.urlopen(request)
html=response.read().decode('utf-8')
# 因为是JSON格式,需要要用padas对JSON格式进行解析
import pandas as pd
from io import StringIO
df = pd.read_json(StringIO(html))
# 获取到了最原始的JSON格式
#挑选主要信息
df[['rank','rating','title','actors']].set_index('rank')

上面仅仅是获取单页的,下面的就来尝试获取多页的

根据URL可以看出,每一页的变化为 <start部分有了数字变化>

复制代码
1. https://movie.douban.com/j/chart/top_list?type=25&interval_id=100%3A90&action=&start=0&limit=20
2. https://movie.douban.com/j/chart/top_listtype=25&interval_id=100%3A90&action=&start=20&limit=20
3. https://movie.douban.com/j/chart/top_listtype=25&interval_id=100%3A90&action=&start=40&limit=20
4. https://movie.douban.com/j/chart/top_listtype=25&interval_id=100%3A90&action=&start=60&limit=20
python 复制代码
import time
import pandas as pd 
import random
from io import StringIO
data=pd.DataFrame()
for i in range(7):
    print('正在爬取第%d页'%i)
    i=i*20
    baseurl='https://movie.douban.com/j/chart/top_list?type=25&interval_id=100%3A90&action=&start' #url前面不变的地方
    url = baseurl+str(i)+'&limit=20'
    headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
    request = urllib.request.Request(url,headers=headers)
    response = urllib.request.urlopen(request)
    html=response.read().decode('utf-8')
    df = pd.read_json(StringIO(html))
    data=pd.concat([data,df])
    time.sleep(random.randint(6,8))#每爬取一次,随机休息
print('爬取完毕')
data[['rank','rating','title','actors']].set_index('rank')
相关推荐
dme.4 分钟前
Javascript之DOM操作
开发语言·javascript·爬虫·python·ecmascript
加油吧zkf14 分钟前
AI大模型如何重塑软件开发流程?——结合目标检测的深度实践与代码示例
开发语言·图像处理·人工智能·python·yolo
t_hj15 分钟前
python规划
python
czhc114007566330 分钟前
Linux 76 rsync
linux·运维·python
悠悠小茉莉1 小时前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
m0_625686551 小时前
day53
python
Real_man2 小时前
告别 requirements.txt,拥抱 pyproject.toml和uv的现代Python工作流
python
K哥爬虫2 小时前
【APP逆向百例】某品会 app 逆向分析
爬虫
站大爷IP2 小时前
Python文件操作的"保险箱":with语句深度实战指南
python
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程