数据分析——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')
相关推荐
m0_547486665 分钟前
《Python程序设计:从基础开发到数据分析》全套PPT课件2026
数据分析·python程序设计
东莞市云毅网络有限公司7 分钟前
用标准库做网页正文抽取:从 HTML 到结构化字段的轻量实现
python·sqlite·自动化运维·geo·数据监测
高级程序源12 分钟前
django校企合作实习基地管理系统82506-计算机课程设计、毕业设计
vue.js·后端·python·mysql·django·课程设计·pygame
东方芷兰13 分钟前
Agent 技术摘要 02 —— 区块链、比特币、挖矿、ETF、比特币疯涨事件、以太坊、以太币、显卡荒事件
人工智能·笔记·python
贝猫说python24 分钟前
阿里云部署qwen 大模型从0-1,第2步:阿里云平台创建ubuntu实例
python
峥嵘life24 分钟前
2026华为AI码道 CodeArts 使用分享:Windows端 + 服务器CLI 实战总结
android·大数据·开发语言·python
贝猫说python25 分钟前
阿里云部署qwen 大模型从0-1,第3步:阿里云服务器上部署大模型
python
少陽君29 分钟前
服务器服务检查报告
python
x秀x30 分钟前
sam3新手使用教程
开发语言·python
Java后端的Ai之路31 分钟前
大模型LLM评估完全指南
开发语言·人工智能·python·llm·评估