2024年最新Python爬虫笔记汇总

#实例2:爬取亚马逊商品详情页————协议头
url='https://www.amazon.cn/dp/B076YGLN6G?smid=A3CQWPW49OI3BQ&ref\_=Oct\_CBBBCard\_dsk\_asin2&pf\_rd\_r=X83064H6KVVDTZ4WWDFB&pf\_rd\_p=5a0738df-7719-4914-81ee-278221dce082&pf\_rd\_m=A1AJ19PSB66TGU&pf\_rd\_s=desktop-3'
try:
    res = requests.get(url)
    res.raise\_for\_status()        #503
    res.encoding=r.apparent_encoding   #'ISO-8859-1'
    print(res.text[:1000])
except:
    print("爬取错误")

'''
res.request.headers
Out[7]: {'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '\*/\*', 'Connection': 'keep-alive'}
'''

try:
    kv={'user-agent':'Mozilla/5.0'}  #浏览器身份标识的字段
    r=requests.get(url,headers=kv)
    r.raise\_for\_status()  #r.status_code   200
    r.encoding=r.apparent_encoding
    print(r.text[1000:3000])
except:
    print("爬取失败")

  1. 百度/360搜索关键字
#实例3:爬取搜索页面
import requests
try:
    kw={'wd':'python'}
    r=requests.get('https://www.baidu.com/s',params=kw)
    r.raise\_for\_status()
    r.encoding=r.apparent_encoding
    print(len(r.text))
    #r.request.url 返回的是百度安全验证的链接?
except:
    print("爬取失败")


import requests
try:
    kw={'q':'python'}  #360搜索的关键字的键为q
    r=requests.get('https://www.so.com/s',params=kw)
    r.raise\_for\_status()
    r.encoding=r.apparent_encoding
    print(len(r.text))  #257468
except:
    print("爬取失败")

  1. 网络图片爬取及存储
#实例4:爬取图片
'''r.content #表示返回内容的二进制格式'''
import requests
import os
root='./Pic/'
path=root+url.split('/')[-1].split('@')[0]
url='http://img0.dili360.com/ga/M00/02/AB/wKgBzFQ26i2AWujSAA\_-xvEYLbU441.jpg@!rw9'
try:
    if not os.path.exists(root):
        os.mkdir(root)  #创建根目录
    if not os.path.exists(path):

        r=requests.get(url)
        # 如何将二进制转化为图片保存
        with open(path, 'wb') as f:
            f.write(r.content)
            f.close()
            print('图片保存成功')
    else:
        print('文件已存在')
except:
    print("爬取失败")

  1. IP地址归属地查询
#实例5:IP地址归属地查询
import requests
url='http://www.ip138.com/iplookup.asp?ip='
try:
    r=requests.get(url+'183.216.163.144',headers=kv)
    r.raise\_for\_status()
    r.encoding=r.apparent_encoding
    print(r.text[:-500])
except:
    print('爬取失败')

二、urllib.request基础

1.urllib基础:

urllib.request.urlretrieve(url,file)  #将网页保存到本地,参数为抓取的网址和保存网页的文件路径
urllib.request.urlcleanup()    #将urlretrieve产生的缓存清除
file=urllib.request.urlopen(url)  #爬取网页
file.info()    #获取header的信息
file.getcode()   #获取爬取网页的状态码(200,403,404等)
file.geturl()     #获取目前爬取的网址

2.超时设置:根据网速和对方服务器响应的快慢设置相应的超时设置

urllib.request.urlopen("http://read.douban.com/provider/all",timeout=1)

for i in range(0,100):
    try:
        file=urllib.request.urlopen("http://www.hao123.com",timeout=10)
        data=file.read()
        print(i,len(data))
    except Exception as e:
        print("出现异常"+str(e))

3.自动模拟http请求:

①get请求(搜索某些内容)

自动在百度上搜索关键词,获得搜索界面

#get请求

keywd="Python"
url="http://www.baidu.com/s?wd="+keywd  #网址构造
print(url)
req=urllib.request.Request(url) #以请求的方式获取,网址
data=urllib.request.urlopen(req).read()

fh=open("C:/Users/admin/Desktop/a.html","wb") #以二进制写入html文件
fh.write(data)
fh.close()

#若搜索关键词为中文
keywd1="亚马孙"
keywd1=urllib.request.quote(keywd1)  #利用quote对中文进行编码
url1="http://www.baidu.com/s?wd="+keywd1
req=urllib.request.Request(url1)
data=urllib.request.urlopen(req).read()

fh=open("C:/Users/admin/Desktop/a.html","wb") #二进制
fh.write(data)
fh.close()

②post请求(登录某些网站)

#post请求
import urllib.request
import urllib.parse

url="https://www.iqianyue.com/mypost/"  #地址
login=urllib.parse.urlencode(
    {"name":"1121640425@qq.com","pass":"123"}
).encode("utf-8")  #登录数据
req=urllib.request.Request(url,login)

data=urllib.request.urlopen(req).read()

fh=open("C:/Users/admin/Desktop/a.html","wb")
fh.write(data)
fh.close()

三、bs4库

功能:解析、遍历、维护标签树。

  • 标签名 p
  • 属性名称 class
  • 属性值 title

3.1 BeautifulSoup支持的解析器

1.Python标准库:内置库、执行速度适中、文档容错能力强;

2.lxml HTML解析器:速度快,文档容错能力强(推荐);

3.lxml XML解析器:速度快,唯一支持xml的解析器;

4.html5lib:最好的容错性、以浏览器方式解析文档,生成HTML5格式的文档。

具体用法:soup=BeautifulSoup(markup,from_encoding=“编码方式”)

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><span> Elsie </span></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.prettify()) #输出清晰的树形结构

Beautifu Soup将复杂的HTML文档转化为树形结构,每个节点都是Python对象:

  • Tag:标签;
  • NavigableString:被包裹在tag内的字符串;
  • BeautifulSoup:表示一个文档的全部内容,大部分时候可以看做一个tag对象,支持遍历文档树和搜索文档树的方法;
  • Comment:特殊NavigableString,会以特殊格式输出,比如注释类型。

3.2 基本用法

搜索文档树:tag.name_按顺序获得第一个标签
在这里插入图片描述
获取所有标签?
在这里插入图片描述
tag.contents可以将tag的子节点以列表方式输出
在这里插入图片描述
tag.children,对tag的子节点进行循环

tag.descendants,子孙节点
在这里插入图片描述
tag.string,获取tag(只有一个子节点)下所有的文本内容
在这里插入图片描述
迭代的方式找出所有的文本内容
在这里插入图片描述
soup.get_text() #从文档中获取所有的文字内容
在这里插入图片描述
在这里插入图片描述

四、正则(信息提取)

在这里插入图片描述

  • 中国大学排名案例
import requests
from bs4 import BeautifulSoup
import bs4

#爬取信息
def getHtmlText(url):
  try:
    res=requests.get(url,timeout=30)
    res.raise\_for\_status()
    res.encoding=res.apparent_encoding
    return res.text
  except:
    print("error")
    return ""

#提取信息
def fillUnivList(ulist,html):
  soup=BeautifulSoup(html,"html.parser")
  for tr in soup.find("tbody").children:
    if isinstance(tr,bs4.element.Tag): #检测tr标签的类型
      tds=tr('td')
      ulist.append([tds[0].string,tds[1].string,tds[2].string])

#打印信息  
def printUnivList(ulist,num): #学习数量
  tplt="{0:^10}\t{1:{3}^12}\t{2:^9}" #{}域,格式化输出
  #表头
  print(tplt.format("排名","学校","地址",chr(12288)))
  for i in range(num):
    u=ulist[i]
    print(tplt.format(u[0],u[1],u[2],chr(12288)))
  print("Suc"+str(num))

#chr(12288)中文空格,解决中英文混排的问题

def mian():
  uinfo=[]


### 最后

> **🍅 硬核资料**:关注即可领取PPT模板、简历模板、行业经典书籍PDF。  
> **🍅 技术互助**:技术群大佬指点迷津,你的问题可能不是问题,求资源在群里喊一声。  
> **🍅 面试题库**:由技术群里的小伙伴们共同投稿,热乎的大厂面试真题,持续更新中。  
> **🍅 知识体系**:含编程语言、算法、大数据生态圈组件(Mysql、Hive、Spark、Flink)、数据仓库、Python、前端等等。




**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里无偿获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值