Python抓取数据知识汇总

Python抓取数据知识汇总,第1张

1. Python爬虫基础 1.1 第一个爬虫程序

通过搜索charset查看网页编码,常用编码有utf-8、jbk

from urllib.request import urlopen

url = "http://www.baidu.com"
resp = urlopen(url)
# read获取的是字节码,然后解码
content = resp.read().decode('utf-8')
print(content)
1.2 Web请求过程解析

包括两种:

  • 服务端渲染数据
  • 客户端渲染数据

https://blog.csdn.net/m0_56289903/article/details/122369002

1.3 Http协议

https://blog.csdn.net/m0_56289903/article/details/122369002

1.4 requests模块安装和使用

requests模块是一个第三方模块,在爬虫任务中 *** 作起来非常简答
1. 安装

pip install requests

2. response响应对象: 打印响应内容

print(response.text)
print(response.content.decode("编码")) # 注意这里!
print(response.json()) # 自动将json字符串类型的的响应内容转化为python对象(dict or list)
  • response.text是requests模块按照chardet模块推测出的编码字符集进行解码的结果

  • 网络传输的字符串都是bytes类型的,所以response.text = response.content.decode(‘推测出的编码字符集’)

  • 我们可以在网页源码中搜索charset,尝试参考该编码字符集,注意存在不准确的情况

常见字符编码: utf-8 、gbk、gb2312、ascii 、iso-8859-1

3. response响应对象的其它常用属性或方法

response.url  响应的url;有时候响应的url和请求的url并不一致
response.status_code 响应状态码
response.request.headers 响应对应的请求头
response.headers 响应头
response.request._cookies  响应对应请求的cookie;返回cookieJar类型
response.cookies  响应的cookie(经过了set-cookie动作;返回cookieJar类型
response.json()  自动将json字符串类型的响应内容转换为python对象(dict or list)
1.5 requests发送get请求

1. 发送get请求

import requests
content = input("请输入要检索的内容:")
url = f"https://www.sogou.com/web?query={content}"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36"
}

resp = requests.get(url, headers=headers)
# print(resp.text)
print(resp.request.headers)

如果不加headers信息,会被服务检测为异常请求: 用户您好,我们的系统检测到您网络中存在异常访问请求 ,从而不会返回数据。


查看头信息

{'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Cookie': 'ABTEST=0|1649174618|v17; SNUID=A744665348429CA22409CA6F4821395A; IPLOC=CN4403; SUID=E0032E1B4322910A00000000624C685A'}

2.处理很多参数的get请求: 使用params

import requests

import requests

url = "https://movie.douban.com/j/chart/top_list"
params = {
    "type": "24",
    "interval_id": "100:90",
    "action": "",
    "start": "0",
    "limit": "20",
}
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36"
}
resp = requests.get(url, params=params, headers=headers)
print(resp.status_code)
print(resp.json())

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/570310.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存