数据分析——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打开
#get请求,访问百度
import urllib.request
response=urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))#decode就是解码后的响应
response.status #响应状态
response.getheaders() #响应头

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

#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())
#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基本原理}

案例

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

## 获取网页的源代码
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数据格式)
         涉及到爬取多页内容

# 获取网页的源代码
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
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')

相关推荐

  1. 数据分析——Python网络爬虫(){爬虫使用}

    2024-07-15 20:50:05       20 阅读
  2. 使用Python进行网站爬虫数据分析

    2024-07-15 20:50:05       32 阅读
  3. 爬虫02-python爬虫使用及详解

    2024-07-15 20:50:05       52 阅读
  4. 基于Python旅游网站数据爬虫分析

    2024-07-15 20:50:05       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-15 20:50:05       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-15 20:50:05       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-15 20:50:05       57 阅读
  4. Python语言-面向对象

    2024-07-15 20:50:05       68 阅读

热门阅读

  1. 数据分析_计划

    2024-07-15 20:50:05       22 阅读
  2. FPGA之术语

    2024-07-15 20:50:05       18 阅读
  3. [C++ 基础入门 - inline和 nullptr]

    2024-07-15 20:50:05       17 阅读
  4. STL常用容器及使用总结

    2024-07-15 20:50:05       21 阅读
  5. MiniCPM-V

    MiniCPM-V

    2024-07-15 20:50:05      20 阅读
  6. Mybatis

    Mybatis

    2024-07-15 20:50:05      18 阅读
  7. ORA-12518: TNS: 监听程序无法分发客户机连接

    2024-07-15 20:50:05       14 阅读
  8. 解决PyCharm配置错误:深入剖析与实战指南

    2024-07-15 20:50:05       22 阅读
  9. 关于VUE2在页面离开时,丢弃所有未完成的请求

    2024-07-15 20:50:05       19 阅读
  10. 使用js对文本框设置字数限制

    2024-07-15 20:50:05       20 阅读
  11. Spring boot 2.0 升级到 3.3.1 的相关问题 (一)

    2024-07-15 20:50:05       17 阅读