今日内容概要

  • IP代理池的概念及使用

  • requests其他方法补充

  • Beautifulsoup模块

    避免你自己写正则表达式

  • 利用该模块爬取京东的商品信息

今日内容详细

IP代理池的概念及使用

1.有很多网站在防爬措施上面都加了封禁IP的措施
一旦我的网站发现某一个IP在固定的时间内访问了很多次(一分钟访问了30次),那么我会直接获取到该请求对应的主机IP地址,然后加入网站的黑名单
刚请求来访问我的网站的时候我会先去黑名单中查看当前请求的IP在不在如果在直接拒绝
如果不在才会进去下一个环节 针对上述IP封禁的情况,出现了IP代理池
IP代理池里面有很多IP,你每次访问别人的网站的时候
随机从池子里面有很多IP 具体使用 # 代理的网址获取有免费的也有收费的
import requests
proxies={'https':'123.163.117.55:9999',
'https':'123.163.117.55:9999',
'https':'123.163.117.55:9999',
}
respone=requests.get('https://www.12306.cn',
proxies=proxies) print(respone.status_code)

超时设置

#超时设置
#两种超时:float or tuple
#timeout=0.1 #代表接收数据的超时时间
#timeout=(0.1,0.2)#0.1代表链接超时 0.2代表接收数据的超时时间 import requests
respone=requests.get('https://www.baidu.com',
timeout=0.0001)

异常处理

# 万能异常
try:
# kasd
l = [111,222]
l[3]
except Exception as e:
print(e)

发送文件

import requests
files={'file':open('a.txt','rb')}
respone=requests.post('http://httpbin.org/post',
files=files)
print(respone.status_code)

解析json

#解析json
import requests
response=requests.get('http://httpbin.org/get') import json
res1=json.loads(response.text) #太麻烦 res2=response.json() #直接获取json数据 print(res1 == res2) #True

Beautiful Soup模块

Beautiful Soup会帮你节省数小时甚至数天的工作时间

# 安装 Beautiful Soup
pip install beautifulsoup4 # 这个4千万不要少了 # 解析器
有四种 常用的两种
html.parse 内置的不需要下载
lxml 需要下载
pip3 install lxml # 导入
from bs4 import BeautifulSoup

基本使用

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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">Elsie</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 # 先将html页面内容传入BeautifulSoup 生成一个对象
soup = BeautifulSoup(html_doc, 'lxml') # 具有容错功能 res = soup.prettify() # 处理好缩进,结构化显示 美化
print(res)

爬取汽车之家新闻

1.爬取汽车之家的新闻数据
2.先查看汽车之家新闻加载规律
默认会先展示一个ul
下面隐藏了三个ul
最后有一个分页器
3.研究分页页码变化
https://www.autohome.com.cn/news/1/#liststart
https://www.autohome.com.cn/news/2/#liststart
https://www.autohome.com.cn/news/3/#liststart
https://www.autohome.com.cn/news/4/#liststart
4.访问新闻数据页 研究是否有一些简单的防爬措施
5.研究新闻数据都在哪个标签内
6.从标签内提取想要的新闻数据,并移除干扰项 # 代码
res = requests.get(url) # 前期访问没有任何的小防爬措施
# print(res.text) # 将爬取到的页面传入bs4类中生成对象
soup = BeautifulSoup(res.text,'lxml')
# 查找新闻所在的标签 然后获取标签内想要的数据
# 1.查找div标签
div = soup.find(id='auto-channel-lazyload-article') # 利用id查找标签
# print(div) # 2.找ul标签
ul = div.find(name='ul') # 利用标签名查找标签 只拿第一个
# ul_list=div.find_all(class_="article") #找出下面所有类名为article的标签 class关键字所以需要加下划线区分
# print(len(ul_list))
# print('+++++++++++++++++++++++++++')
# print(ul) # 3.找li标签
# li = ul.find(name='li') # 只会拿到第一个
li_list = ul.find_all(name='li') # 拿内部所有的li 并且组织成列表的形式
# 4.从li中提取我们想要的数据
"""
<li data-artidanchor="1038223">
<a href="//www.autohome.com.cn/news/202009/1038223.html#pvareaid=102624">
<div class="article-pic"><img src="//www2.autoimg.cn/newsdfs/g3/M01/B5/C1/120x90_0_autohomecar__ChsEkV9i0DiAKHchAAGGvdkeT_A835.jpg"/></div>
<h3>主打年轻化市场 宝马128ti低伪谍照曝光</h3>
<div class="article-bar">
<span class="fn-left">30分钟前</span>
<span class="fn-right">
<em><i class="icon12 icon12-eye"></i>827</em>
<em data-articleid="1038223" data-class="icon12 icon12-infor"><i class="icon12 icon12-infor"></i>0</em>
</span>
</div>
<p>[汽车之家 海外谍照] 日前,宝马集团官方放出了一组宝马128ti的轻度伪装图,这款车已在纽博格林赛道完成了最后的测试,并将于11月在海外市场投放。...</p>
</a>
</li>
"""
# for循环依次获取数据
for li in li_list:
# 1.先获取新闻的标题
h3 = li.find(name='h3')
# print(h3)
# 优化 移除干扰项
if h3:
# 获取h3里面的文本
news_title = h3.text
# print(news_title) # 2.获取新闻链接
a = li.find(name='a')
# 移除干扰项
if a:
news_link = a.get('href')
# print(news_link)
# 3.获取图片链接
img = li.find(name='img')
if img:
news_img = img.get('src')
# print(news_img) # 4.获取新闻简介
p = li.find(name='p')
if p:
news_info = p.text
# print(news_info) res = """
新闻标题:%s
新闻链接:%s
新闻图片:%s
新闻简介:%s
"""%(h3,news_link,news_img,news_info)
print(res)

更多操作方法

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title jason" username="jason">123<b id="bbb" class="boldest">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">Elsie</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_doc,'lxml') # print(soup.a) # 查找a标签 只会拿第一个 # print(soup.p.name) # 获取标签名 # print(soup.p.attrs) # 用字典的形式给你列举出标签所有的属性
# {'id': 'my p', 'class': ['title'], 'username': 'jason'} print(soup.p.text) # 获取p标签内部所有的文本
# string用的很少
# print(soup.p.string) # 只有p下面有单独的文本的时候才能拿到

总结

1.查找标签非常的简单
find()
find_all()
"""
括号内常用的参数
name 根据标签的名字查找标签
id 根据标签的id查找标签
class_ 根据标签的class查找
""" 2.查找标签内部的文本
标签对象.text 3.查找标签属性对应的值
a标签的href属性对应的值
a.get('href')
img标签的src属性对应的值
img.get('src')

爬虫之Beautfulsoup模块及新闻爬取操作的更多相关文章

  1. python爬虫学习之使用BeautifulSoup库爬取开奖网站信息-模块化

    实例需求:运用python语言爬取http://kaijiang.zhcw.com/zhcw/html/ssq/list_1.html这个开奖网站所有的信息,并且保存为txt文件和excel文件. 实 ...

  2. 另类爬虫:从PDF文件中爬取表格数据

    简介   本文将展示一个稍微不一样点的爬虫.   以往我们的爬虫都是从网络上爬取数据,因为网页一般用HTML,CSS,JavaScript代码写成,因此,有大量成熟的技术来爬取网页中的各种数据.这次, ...

  3. Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(人人网)(下)

    Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(下) 自动使用cookie的方法,告别手动拷贝cookie http模块包含一些关于cookie的模块,通过他们我们可以自动的使用co ...

  4. python网络爬虫之解析网页的BeautifulSoup(爬取电影图片)[三]

    目录 前言 一.BeautifulSoup的基本语法 二.爬取网页图片 扩展学习 后记 前言 本章同样是解析一个网页的结构信息 在上章内容中(python网络爬虫之解析网页的正则表达式(爬取4k动漫图 ...

  5. scrapy中间件之下载中间件使用(网易新闻爬取)

    scrapy项目中的middlewarse.py中间件 爬虫中间件:目前先不介绍 下载中间件(需要在settings.py中开启) (1)请求处理函数:process_request(self, re ...

  6. scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250

    scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250 前言 经过上一篇教程我们已经大致了解了Scrapy的基本情况,并写了一个简单的小demo.这次我会以爬取豆瓣电影TOP250为例进一步为大 ...

  7. 爬虫系列4:Requests+Xpath 爬取动态数据

    爬虫系列4:Requests+Xpath 爬取动态数据 [抓取]:参考前文 爬虫系列1:https://www.cnblogs.com/yizhiamumu/p/9451093.html [分页]:参 ...

  8. 爬虫简单之二---使用进程爬取起点中文网的六万多也页小说的名字,作者,等一些基本信息,并存入csv中

    爬虫简单之二---使用进程爬取起点中文网的六万多也页小说的名字,作者,等一些基本信息,并存入csv中 准备使用的环境和库Python3.6 + requests + bs4 + csv + multi ...

  9. [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息

    [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息 2018-07-21 23:53:02 larger5 阅读数 4123更多 分类专栏: 网络爬虫   版权声明: ...

随机推荐

  1. bom案例4-模拟滚动条

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  2. Java泛型T与?

    感谢大佬:http://m.mamicode.com/info-detail-2657551.html 一.区别 单独的T 代表一个类型 ,而 Class<T>代表这个类型所对应的类, C ...

  3. Redis 源码简洁剖析 10 - aeEventLoop 及事件

    aeEventLoop IO 事件处理 IO 事件创建 读事件处理 写事件处理 时间事件处理 时间事件定义 时间事件创建 时间事件回调函数 时间事件的触发处理 参考链接 Redis 源码简洁剖析系列 ...

  4. Vue3.X安装

    1.查看node.js和npm版本 $ node -v //建议v10以上版本 $ npm -v 2.若已安装了2.x的旧版本,需要先卸载 npm uninstall vue-cli -g 3.安装淘 ...

  5. linxu 查看运行日志

    journalctl - 检索 systemd 日志 journalctl 可用于检索 systemd(1) 日志(由 systemd-journald.service(8) 记录). 如果不带任何参 ...

  6. CopyOnWriteList揭秘

    List的并发容器-CopyOnWriteList Vector和SynchronizedList ArrayList是用来代替Vector,Vector是线程安全的容器,因为它在方法上都加上了syn ...

  7. 人工智能——CNN卷积神经网络项目之猫狗分类

    首先先导入所需要的库 import sys from matplotlib import pyplot from tensorflow.keras.utils import to_categorica ...

  8. 对象到底是怎么new出来的

    前言:要想理解本文,必须先了解JVM的内存结构 一.创建对象的方式 new:最常见 反射:Class.newInstance() 使用clone() 反序列化 二.创建对象的步骤(对象在JVM中怎么存 ...

  9. 从浅入深掌握并发执行框架Executor

    引言 任务的执行 大多数并发应用程序都是围绕"任务执行(Task  Execution)"来构造的:任务通常是一些抽象的且离散的工作单元. 任务通常是一些抽象的且离散的工作单元.通 ...

  10. Python:更改pip镜像源的方法

    windows系统一步更换 在命令提示符中运行 pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ 具体其它 ...