python爬虫 基于requests模块的get请求实现详解

yipeiwu_com5年前Python爬虫

需求:爬取搜狗首页的页面数据

import requests
# 1.指定url
url = 'https://www.sogou.com/'
# 2.发起get请求:get方法会返回请求成功的响应对象
response = requests.get(url=url)
# 3.获取响应中的数据:text属性作用是可以获取响应对象中字符串形式的页面数据
page_data = response.text
# 4.持久化数据
with open("sougou.html","w",encoding="utf-8") as f:
  f.write(page_data)
  f.close()
print("ok")

requests模块如何处理携带参数的get请求,返回携带参数的请求

需求:指定一个词条,获取搜狗搜索结果所对应的页面数据

之前urllib模块处理url上参数有中文的需要处理编码,requests会自动处理url编码

发起带参数的get请求

params可以是传字典或者列表

def get(url, params=None, **kwargs):
  r"""Sends a GET request.
  :param url: URL for the new :class:`Request` object.
  :param params: (optional) Dictionary, list of tuples or bytes to send
    in the body of the :class:`Request`.
  :param \*\*kwargs: Optional arguments that ``request`` takes.
  :return: :class:`Response <Response>` object
  :rtype: requests.Response
import requests
# 指定url
url = 'https://www.sogou.com/web'
# 封装get请求参数
prams = {
  'query':'周杰伦',
  'ie':'utf-8'
}
response = requests.get(url=url,params=prams)
page_text = response.text
with open("周杰伦.html","w",encoding="utf-8") as f:
  f.write(page_text)
  f.close()
print("ok")

利用requests模块自定义请求头信息,并且发起带参数的get请求

get方法有个headers参数 把请求头信息的字典赋给headers参数

import requests
# 指定url
url = 'https://www.sogou.com/web'
# 封装get请求参数
prams = {
  'query':'周杰伦',
  'ie':'utf-8'
}
# 自定义请求头信息
headers={
  'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
  }
response = requests.get(url=url,params=prams,headers=headers)
page_text = response.text
with open("周杰伦.html","w",encoding="utf-8") as f:
  f.write(page_text)
  f.close()
print("ok")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python爬取商家联系电话以及各种数据的方法

Python爬取商家联系电话以及各种数据的方法

上次学会了爬取图片,这次就想着试试爬取商家的联系电话,当然,这里纯属个人技术学习,爬取过后及时删除,不得用于其它违法用途,一切后果自负。 首先我学习时用的是114黄页数据。 下面四个是用...

基于python 爬虫爬到含空格的url的处理方法

道友问我的一个问题,之前确实没遇见过,在此记录一下。 问题描述 在某网站主页提取url进行迭代,爬虫请求主页时没有问题,返回正常,但是在访问在主页提取到的url时出现了400状态码(40...

详解爬虫被封的问题

详解爬虫被封的问题

如果你在爬虫过程中有遇到“您的请求太过频繁,请稍后再试”,或者说代码完全正确,可是爬虫过程中突然就访问不了,那么恭喜你,你的爬虫被对方识破了,轻则给予友好提示警告,严重的可能会对你的ip...

python正则表达式爬取猫眼电影top100

用正则表达式爬取猫眼电影top100,具体内容如下 #!/usr/bin/python # -*- coding: utf-8 -*- import json # 快速导...

python爬取指定微信公众号文章

本文实例为大家分享了python爬取微信公众号文章的具体代码,供大家参考,具体内容如下 该方法是依赖于urllib2库来完成的,首先你需要安装好你的python环境,然后安装urllib...