python爬虫—–Python访问http的几种方式「建议收藏」
python,爬虫,Python,访问,http,几种,方式,建议,收藏
2025-04-01 16:27:55 时间
大家好,又见面了,我是你们的朋友全栈君。
爬取页面数据,我们需要访问页面,发送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
相关文章
- 终于来了, 彭涛Python 爬虫训练营 !爬虫福利倒计时,速度,下周涨价!
- python爬虫的4个实例
- 终于来了, 彭涛Python 爬虫训练营 !爬虫课福利进行中,务必不要错过!
- Python爬虫之验证码识别
- [Python 爬虫]煎蛋网 OOXX 妹子图爬虫(1)——解密图片地址
- Python爬虫之scrapy框架
- python 网络爬虫入门(一)———第一个python爬虫实例
- Python 爬虫 NO.1 URI和URL
- Python 万能代码模版:爬虫代码篇「建议收藏」
- Python招聘岗位信息聚合系统源码(爬虫爬取、数据分析、可视化、互动等功能)
- Python爬虫之requests
- 【Python】 "爬虫"出发前的装备之一正则表达式
- Python - 手把手教你用Scrapy编写一个爬虫
- Python爬虫数据抽取(三):pyquery库「建议收藏」
- 全网最全python爬虫精进
- Python获取时间戳_python爬虫时间戳
- Python爬虫之多线程
- Python爬虫之数据写入
- python和pythoncharm有什么区别_python为什么叫爬虫
- Python爬虫(全)