爬虫基础笔记--爬取网页数据

使用urllib实现数据传输

传递数据的方式主要分为两种GET和POST。
GET:直接使用 URL访问,在URL中包含了所有的参数
POST:不会在URL中显示所有参数

URL编码转换

需要使用urllib.parse库中的urlencode()方法将URL进行编码

import urllib.parse
data={
    'a':'黑马程序员',
    # a与b 之间要用  ,  分隔
    'b':'hello world'
}
result=urllib.parse.urlencode(data)
print(result)

# 结果  a=%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98&b=hello+world

解码使用urlparse库的unquote()方法

result2=urllib.parse.unquote('a=%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98')
print(result2)
# 结果  a=黑马程序员

处理GET请求

GET请求一般用于向服务器获取数据 例如用百度搜索黑马程序员(URL是https://www.baidu.com/s?wd=%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98)

import  urllib.request
import  urllib.parse
url="http://www.baidu.com/s"
word={"wd":"黑马程序员"}
word=urllib.parse.urlencode(word)
new_url=url+"?"+word
headers={"User-Agent":"Mozilla/5.0 (Window NT  10.0;WOW64) AppleWebKit/537.36  (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
requests=urllib.request.Request(new_url,headers=headers)
response=urllib.request.urlopen(requests)
html=response.read().decode('UTF-8')
print(html)

处理POST请求

以POST方式发送请求,urlopen()方法必须设置data参数。data参数以字典的形式存放数据

添加特定的Headers—请求伪装

将爬虫程序伪装成一个从浏览器发出的请求,需要自定义请求报头在发送request请求时,加入特定的Headers
只需要调用Request.get——header()

import urllib.request
url="http://www.itcast.cn"
user_agent={"User-Agent":"Mozilla/5.0 (compatible; MSIE  9.0; Windows NT 6.1; Trident/5.0)"}
request=urllib.request.Request(url,headers=user_agent)
# 也可以通过调用Request.add.——headers() 添加/修改一个特定的header
request.add_header("Connection","keep-alive")
#也可以通过调用Request.get_header() 来查看header信息
request.get_header(header_name="Connection")
response=urllib.request.urlopen(request)
print(response.code)
html=response.read()
print(html)

代理服务器

-----网站限制IP访问的次数,—代理多用于防止“放爬虫”机制

简单的自定义opener

opener是urllib.request.OpenerDirector类的对象,之前使用的urlopen就是模块构建好的一个opener,但不支持代理 Cookie等其他的HTTP/HTTPS高级功能

1.使用相关的Handler处理器创建特定功能的处理器对象
2.通过urllib.request.build_opener()方法使用处理器对象创建自定义的opener对象
3.使用自定义的opener对象,调用open()方法发送请求

import urllib.request
# 构建一个HTTPHander处理器对象,支持处理HTTP请求
import requests

http_hanlder=urllib.request.HTTPHandler()
# 调用urllib2.build_opener()方法,创建支持处理HTTP请求的opener对象
opener=urllib.request.build_opener(http_hanlder)
request=urllib.request.Request("http://www.baidu.com/")
response=opener.open(request)
print(response.read())

设置代理服务器
可以使用urllib.request中的ProxyHandler()方法

import urllib.request
httpproxy_handler=urllib.request.ProxyHandler({"http":"172.16.221.70"})
nullproxy_handler=urllib.request.ProxyHandler({})
proxy_switch=True

if proxy_switch:
    opener=urllib.request.build_opener(httpproxy_handler)
else:
    opener=urllib.request.build_opener(nullproxy_handler)
request=urllib.request.Request("http://www.baidu.com/")
response=opener.open(request)
print(response.read())

常见的网络异常

当使用urlopen()方法发送HTTP请求时,如果urlopen不能处理返回的响应内容,就会产生错误

URLError异常和捕获

URLError产生的原因主要亚欧以下几种:
1.没有连接网络
2.服务器连接失败
3.找不到指定的服务器
可以使用try…except…语句捕获相应的异常

import urllib.request
import urllib.error
request=urllib.request.Request("http://www.ajkfhafwjqh.com")
try:
    urllib.request.urlopen(request,timeout=5)
except urllib.error.URLError as err:
    print(err)

# 结果:<urlopen error [Errno 11004] getaddrinfo failed>

HttpError异常和捕获

每个服务器的HTTP响应都会有一个数字响应码,有些表示无法处理请求内容,则会抛出异常
HttpError 是URLError的子类

requests库

requests 库

继承了urllib的所有特性,而且还支持一些其他的特性
1.requests.Requests:表示请求对象,将一个请求发送到服务器
2:requests.Response:表示响应对象,其中包含服务器对HTTP的响应
3.requests.Session:表示请求会话,支持Cookie持久性、连接池和配置

使用requests库GET请求爬取网页

import request
url="http://www.baidu.com/s"
param={"wd":"传智播客"}
headers={"User-Agent":"Mozilla/5.0 (Window NT  10.0;WOW64) AppleWebKit/537.36  (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
response=requests.get(url,params=param,headers=headers)
print(response.text)

发送请求

requests.request() :构造一个请求,支持以下方法的基础方法
requests.get() :获取HTML网页的主要方法,对应于HTTP的GET请求
requests.head() :获取HTML网页头信息的方法,对应HEAD请求方式
requests.post() :向HTML网页提交POST请求方法
.put() : PUT
.patch() :提交局部修改请求
.delete() : 删除请求

返回请求

ststus_code 200表示成功,404表示失败
text URL对应的页面内容
encoding 从请求头中猜测响应内容编码的方式
apparent_encoding 分析出响应编码的方式
content 响应内容的二进制形式

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当使用Python进行网页爬取时,切换句柄可能会导致无法正确获取网页数据。要解决这个问题,可以尝试以下方法: 1. 使用Selenium库中的`switch_to.window()`方法来切换句柄。可以参考[Selenium官方文档](http://selenium-python.readthedocs.io/api.html#switch_to)中的相关内容,了解如何正确切换句柄。 2. 确保在切换句柄之前,等待新页面完全加载完成。可以使用Selenium中的显式等待或隐式等待来确保页面加载完毕。具体的等待方法可以参考[Selenium官方文档](http://selenium-python.readthedocs.io/waits.html)中的相关内容。 3. 如果切换句柄后仍然无法获取网页数据,可能是因为页面中的数据使用了AJAX或者动态加载的方式。可以尝试使用Selenium中的`execute_script()`方法来模拟用户操作,例如滚动页面或点击按钮,以触发数据加载。 总之,切换句柄后无法爬取网页数据可能是由于页面加载延迟或者动态加载引起的。通过使用正确的切换句柄方法和等待策略,以及模拟用户操作,可以解决这个问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Python爬虫,使用selenium爬取动态生成的网页数据 - 旧人笔记 - 旧人学习笔记 - 爬虫笔记 - 网络爬虫大白话](https://blog.csdn.net/weixin_43040873/article/details/109134168)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值