Python抓取数据知识汇总

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())

2.数据解析

常见的数据解析方式有四种,分别是:re解析、bs4解析、xpath解析、pyquery解析。这几种方式完全以结果为导向,可以混合使用。

2.1正则表达式

正则表达式(Regular Expression)是一种使用表达式对字符串进行匹配的语法规则,用于处理字符串

  • 优点:速度快、效率高、准确性高
  • 语法规则:使用元字符进行排列组合用来匹配字符串
  • 元字符:具有固定含义的特殊符号
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值