python爬虫—–Python访问http的几种方式「建议收藏」
2023-06-13 09:12:06 时间
大家好,又见面了,我是你们的朋友全栈君。
爬取页面数据,我们需要访问页面,发送http请求,以下内容就是Python发送请求的几种简单方式:
会使用到的库 urllib requests
1.urlopen
import urllib.request
import urllib.parse
import urllib.error
import socket
data = bytes(urllib.parse.urlencode({"hello": "world"}),encoding='utf8')
try:
response = urllib.request.urlopen('http://httpbin.org/post',data=data,timeout=10)
print(response.status)
print(response.read().decode('utf-8'))
except urllib.error.URLError as e:
if isinstance(e.reason, socket.timeout):
print("TIMEOUT")
2.requests
用到requests中的get post delete put 方法访问请求 这种比一简单一些
每个方法有相应的参数列表,比如 get params参数 proxies:设置代理 auth: 认证 timeout :超时时间 等
import requests
ico = requests.get("https://github.com/favicon.ico")
with open("favicon.ico", "wb") as file:
file.write(ico.content)
3.Request Session
from requests import Session, Request
url = "https://home.cnblogs.com/u/qiutian-guniang/"
s = Session()
req = Request('GET', url=url, headers=header)
pred = s.prepare_request(req)
r = s.send(pred)
print(r.text)
某些网页会禁止抓取数据 我们可以 通过设置User-Agent来设置 使用cookies来保持登录的访问状态例如:以下的cookie内容可以通过在F12控制台获取 复制粘贴 放入headers中
cookies = "_gat=1"
headers = {
"Cookie": cookies,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; '
'x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/68.0.3440.106 Safari/537.36'
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/155864.html原文链接:https://javaforall.cn
相关文章
- pycharm配置python运行环境_C中调用Python
- python语言变量命名规则有什么_Python变量命名规则(超级详细)
- Python 万能代码模版:爬虫代码篇「建议收藏」
- python中bool函数_bool()函数以及Python中的示例
- python hashlib_Python hashlib模块实例使用详解
- python分组聚合_python爬虫标签
- 【说站】Python PyQt菜单的动态填充
- 【说站】python中%如何实现格式化
- python制作自动交易程序_Python如何实现自动化交易
- Python也能画漂亮的complex heatmap?
- Python爬虫 | 美国特斯拉充电桩位置信息(含经纬度)爬取
- Python版比心
- PyDbg安装(《Python 灰帽子》)
- 【Python】字符串 ④ ( Python 浮点数精度控制 | 控制数字的宽度和精度 )
- python实现图片爬虫详解编程语言
- python通过win32com库播放mp3文件详解编程语言
- Python使用map,reduce高阶函数模拟实现Spark的reduceByKey算子功能详解编程语言
- Python 基于python实现的http+json协议接口自动化测试框架源码(实用改进版)详解编程语言
- Python简易操作MySQL数据库指南(python操作mysql数据库)
- Linux查看Python安装路径的方法(linux查看python安装路径)
- Python连接MySQL数据库:初学者指南(python入mysql)
- python远程登录代码
- python文件和路径操作函数小结
- Python爬虫框架Scrapy安装使用步骤
- python字典序问题实例