python(数据分析与可视化)二

python(数据分析与可视化)二

爬取网页内容的前期技术储备

1.pip包管理

(1)内置库

包/库:别人写好的代码,直接引用,加快开发效率。
内置包:python解释器内置常用功能库。
– 解释器安装目录/Lib文件夹下, os time urllib等
– 文件夹里有__init__.py 就成了一个包。

...
import urllib
from urllib import request
response = request.urlopen('http://baidu.com')
...

(2)关于HTTP模拟和HTML源代码解析

python时代: urllib urllib2
由第三方程序员做了一个新http请求库,比官方更方便,urllib3
又有一个程序员,在urllib3基础上进一步封装和优化,requests
python3时代 内置库统一为urllib
结论:建议直接使用requests

(3)第三方库

pypi.org 上丰富的各种功能的库

①pip包管理工具

在服务器上没有图形界面的浏览器.开发语言第三方库往往用命令行包管理工具
解释器/script/pip.exe

pip -V   # 看Pip版本
pip search requests  #搜索包信息
pip install requests  #安装第三方库
pip uninstall requests #卸载
pip list #展示所有已经安装过的库
pip freeze > requirements.txt #把项目用到的库信息导出到一个文件中

第三方库安装的位置: 解释器目录\lib\site-packages\

②换源

软件源source: 清单里维护了上万的 某某软件-> 某某url下载 库下载地址关系,但官方pypi.org下载速度慢,国内一些大学、大公司同步镜像
方法一:临时换源
‘pip install requests -i http://simply.aliyun.com/simply/’
方法二:永久换
系统用户文件夹下新建.pip文件夹和pip.conf文件,写入配置

方式三(推荐):pycharm设置里面配settings/interpreter/+号/manage repositories/+号 复制源(推荐阿里云)

参考[pip换源](https://www.cnblogs.com/believepd/p/10499844.html)
豆瓣 https://pypi.doubanio.com/simple/
阿里云 https://mirrors.aliyun.com/pypi/simple/
清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/

2.requests基本用法

requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pythoner。下面我以代码的形式简单写其中常用的几个知识点:

import requests

baidu_index_url = 'https://baidu.com'
baidu_search_url = 'http://baidu.com/s'

#仿造请求头,基本反爬虫措施
headers = {
    #'cookies':'',     #跟公共参数、用户会话有关
    #'refer':'',       #从哪个页面来
    #浏览器标识,容易伪造,但肯定是机器人,容易被服务器识别出来
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'
}

params = {
    'wd':'天气',
    'ie':'utf-8'
}

response = requests.get(url=baidu_search_url,params=params)
#状态码
status_code = response.status_code
if status_code == 200:
    #网页数据 bytes
    content = response.content
    #网页数据str  一般直接取得text属性,但少数情况解码错误出现乱码
    text = response.text
    text = content.decode('utf-8') #只有百度需要()特殊
    print(text)
    url = response.url
    headers = response.headers

3.debug模式

debug模式也就是调试运行模式
具体操作过程可以分为三步:
1.打断点
2.以debug运行
3.F8向下执行单步,观察变量值

import requests

response = requests.get(url='https://baidu.com', )
# 状态码
status_code = response.status_code
if status_code == 200:
    # 网页数据 bytes
    content = response.content
    # 网页数据str  一般直接取得text属性,但少数情况解码错误出现乱码
    text = response.text
    text = content.decode('utf-8')
    print(text)
    url = response.url
    headers = response.headers

for i in range(10):
    print(i)
    j = i
    j+=1
    print(1)

4.html解析—正则

①我们已经用requests模拟请求,拿到网页源代码,str字符串,里面HTML模式
#需要分析
字符串自带的find方法功能有限,如下:

html = '<html><body><h1>标题</h1></body></html>'
start_index = html.find('<h1>')
end_index = html.find('</h1>')
print(html[start_index:end_index])

因此有三种解析方法:
解析方式一:正则 regex,专门针对字符串处理的语法
(不推荐,了解即可)

import re
text1 = 'ilikepythonbutyouarebeautiful'
pattern1 = re.compile(r'python')
matcher1 = re.search(pattern1,text1)
print(matcher1[0])

text2 = '<h1>i like world</h1>'
pattern2 = re.compile(r'<h1>.+</h1>')  # . 表示一个字符
matcher2 = re.search(pattern2,text2)
print(matcher2[0])

text3 = 'beautiful'
text4 = 'you are a good boy'
text5 = '13243454454@qq.com'
#注册验证邮箱

#手册  https://tool.oschina.net/uploads/apidocs/jquery/regexp.html
#常用正则 https://www.cnblogs.com/qq364735538/p/11099572.html

text6 = """
<html>
aaacc<h1>adsd
sss
</h1>
aaaa
</html>
"""
pattern10 = re.compile(r'<h1>(.*?)</h1>',re.S)
print(pattern10.findall(text6))

#把网页上HTML目标区域标签复制到上述代码中,像抓取的信息用(.*?)代替

5.html解析—bs库(不推荐,了解即可)

#网页HTML本身就是树状层状结构,按照层次去找
#beautiful-soup库 是python2时代的库,
#适合python3的是beautifulsoup4
#用’pip install beautifulsoup4‘来安装第三方库

from bs4 import BeautifulSoup #小坑:代码包名和包原信息名字不一致

html = """
<html>
  <body>
    <a id='xxx' href="https://baidu.com">百度一下</a>
    <a></a>
  </body>
</html>
"""

#先把字符串解析成html结构,内置库html.parser  或者第三方库lxml
bs = BeautifulSoup(html,'html.parser') #或者第二个参数填入“lxml”
print(bs.a)
print(bs.find_all('a'))
print(bs.a['href'])
print(bs.a)
#获取父、子标签

#总结:bs逻辑直观简单,但代码较多

6.html解析—xpath

#xpath表达式有自己的语法,但没有正则那么复杂,类似bs4库按照html层级查找
#用’pip install lxml‘来进行第三方库的安装

from lxml import etree

html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>lxml中xpath的用法</title>
</head>
<body>
    <ul>
        <li><a href="https://www.baidu.com" class="first_a">百度一下</a></li>
        <li><a href="https://mail.qq.com" id="second_a">QQ邮箱</a></li>
        <li><a href="https://www.taobao.com">淘宝网</a></li>
        <li>
            <a href="https://pypi.python.org" class="first_a">Python官网</a>
            <a href="https://pypi.python.org" class="second_a">Python</a>
        </li>
    </ul>
    <p class="one">first_p_tag</p>
    <p id="second">second_p_tag</p>
    <div class="one">
        first_div_tag
        <p class="first second third">11111111</p>
        <a href="#">22222222</a>
    </div>
</body>
</html>
"""

#把长字符串转换成html文档树
dom = etree.HTML(html)
print(dom)

#默认情况下都是全文匹配,匹配不到返回空列表,匹配到的【element,element】
#  "/"表示往下一层    “//”表示忽略任意层父级目录
dom.xpath('//a')
#取html元素里的属性
# "/@href"取元素属性值
dom.xpath('//a/@href')
#取标签里面的内容 -> "/text()"
print(dom.xpath('//a/text()'))
# 属性过滤
print(dom.xpath('//a[@id="second_a"]/text()')[0])

比较正则xpathbs
难度简单
代码量
可读性

今天的分享就到这里,如果还想了解更多,可以看我主页!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值