Python入门网络请求与解析

Posted 白玉梁

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python入门网络请求与解析相关的知识,希望对你有一定的参考价值。

安装网络请求模块:Requests

pip install requests

是否似曾相识?是否想起了nodejs?

简单测试:

先导入requests模块:

import requests

get请求:

response = requests.get("https://www.baidu.com")
print(response)

结果:

说明已经请求成功了,我们可以在编辑器中查看response中都有什么:

打印response.text:

这个就是百度首页内容,不过乱码了,别着急,加上这一步:

response = requests.get("https://www.baidu.com")
response.encoding = response.apparent_encoding
print(response.text)


OK!是不是灰常简单?

当然,requests不仅仅支持get,同样也支持post,put,delete等:

在具体使用不同请求方式时,同样也支持headler,param等等:

requests.get("https://www.baidu.com",headers=,params=)

这是网络请求框架必不可少的!

我们以360图片接口为例,进行分页请求:http://wallpaper.apc.360.cn/index.php?c=WallPaperAndroid&a=getAppsByCategory&cid=9&start=0&count=99

当然,我们可以直接通过get请求该链接,也可以通过post请求并传入参数:

params = 
    'c': 'WallPaperandroid',
    'a': 'getAppsByCategory',
    'cid': 9,
    'start': 0,
    'count': 10

response = requests.post("http://wallpaper.apc.360.cn/index.php", params=params)
print(response.text)

请求结果(json格式):

解析json:

json_data = json.loads(response.text)
print('errno=%s,errmsg=%s' % (json_data['errno'], json_data['errmsg']))
list = json_data['data']
print("count=" + str(len(list)))

结果:

注意:print打印log时,字符串后面使用+拼接参数时只能时字符串类型,所以需要用str()将int类型转为string类型!

好了,json格式的解析完了,如果我想去解析网页该怎么做呢?我很早以前使用java解析网页时,用到一个工具叫jsoup,相信也有不少同学用过,它时直接按xml格式解析,各种node,element…

python一样有类似且强大的网页解析工具: BeautifulSoup。(:python原生带有xml-sax,xml-dom解析器,但好不好用需要自己体会了!)

BeautifulSoup使用文档

BeautifulSoup优缺点:

我们一般在解析网页数据时,就是用的第二种:BeautifulSoup(markup, “lxml”)!

安装BeautifulSoup:pip install bs4

简单测试,以百度首页为例:

from bs4 import BeautifulSoup

response = requests.get("https://www.baidu.com")
response.encoding = response.apparent_encoding
print(response.text)
soup = BeautifulSoup(response.text, "lxml")
title = soup.find(name='title').text  # 也可以省略name:soup.find('title')
print(title)

执行报错:

Couldn't find a tree builder with the features you requested: lxml. 
Do you need to install a parser library?

解决方案:

1.安装virtualenv:
pip install virtualenv

1.安装lxml:
pip install lxml

再次执行py程序,结果:

以上是关于Python入门网络请求与解析的主要内容,如果未能解决你的问题,请参考以下文章

Python入门网络请求与解析

python网络爬虫入门

python 网络爬虫入门笔记

如何入门 Python 爬虫?人人都能学会

如何入门 Python 爬虫

VSCode自定义代码片段14——Vue的axios网络请求封装