Python网络数据采集读书笔记-1

简介: Python网络数据采集读书笔记-1

第一部分 创建爬虫

第一章 初见网络爬虫

1.1 网络连接

# py3 urllib
from urllib.request import urlopen
url = "http://www.baidu.com"
html = urlopen(url)
print(html.read())

官方文档:https://docs.python.org/3/library/urllib.html


1.2 BeautifulSoup

安装:

pip install beautifulsoup4

官方中文文档:

https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/index.html


推荐使用虚拟环境: Mac安装python环境以及虚拟环境


# py3 BeautifulSoup
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "http://www.baidu.com"
html = urlopen(url)
soup = BeautifulSoup(html.read()) # "html.parser"
print(soup.title)
# <title>百度一下,你就知道</title>

增加异常处理


# 异常处理
# 1、 服务器不存在
# 2、 网页不存在
# py3
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "http://www.baidu.com"
try:
    html = urlopen(url)
except Exception as e:
    print(e)
else:
    soup = BeautifulSoup(html.read(), "html.parser")
    print(soup.title)  # <title>百度一下,你就知道</title>
    tag = soup.xxxxx
    print(type(tag))  # <class 'NoneType'>
finally:
    pass

重新组织代码

# py3
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
from bs4 import BeautifulSoup
def getTitle(url):
    """
    异常处理
    1、 服务器不存在
    2、 网页不存在
    3、 标签不存在
    """
    try:
        html = urlopen(url)
    except (HTTPError, URLError) as e:
        return None
    try:
        soup = BeautifulSoup(html.read(), "html.parser")
        title = soup.head.title
    except AttributeError as e:
        return None
    return title
url = "http://www.baidu.com"
title = getTitle(url)
if title == None:
    print("title is None")
else:
    print(title)
    # < title > 百度一下,你就知道 < / title >

第二章 复杂HTML解析

2.1 标签过滤

find, find_all 参数
name=None,      标签,或运算
attrs={},       属性,与运算
recursive=True, 递归 
text=None,      文本
limit=None,     范围限制  find <=> find_all(limit=1) 
**kwargs,       关键字 class_
url = "http://www.pythonscraping.com/pages/warandpeace.html"
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
name_list = soup.find_all("span", {"class": "green"})
for name in name_list:
    print(name.get_text())
h1 = soup.find(text="Chapter 1")
print(h1)

2.2 BeautifulSoup对象

四个对象:
BeautifulSoup   文档
Tag             标签
NavigableString 标签文字
Comment         注释

2.3 导航树

# 孩子和后代
children 
descendants 
# 兄弟
next_siblings 
previous_siblings 
next_sibling
previous_sibling
# 父亲
parent
parents
url = "http://www.pythonscraping.com/pages/page3.html"
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
table = soup.find("table", {"id": "giftList"})
from bs4.element import Tag
# for tr in table.children:
#     if isinstance(tr, Tag):
#         for td in tr.children:
#             print(td.get_text(), end="|")
#     print("\n")
img = table.find("img", {"src": "../img/gifts/img1.jpg"})
price = img.parent.previous_sibling.get_text()
print(price)

2.4 正则表达式

官方文档:https://docs.python.org/3/library/re.html

参考文章:Python编程:re正则库


正则邮箱:
[A-Za-z0-9\._+]+@[A-Za-z0-9]+\.(com|cn|org|edu|net)

import re


url = "http://www.pythonscraping.com/pages/page3.html"
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
regex = re.compile(r"\.\.\/img\/gifts\/img.*\.jpg")
imgs = soup.find_all("img", {"src": regex})
for img in imgs:
    print(img.get("src")) # 获取属性 attrs

2.5 lambda表达式

# 返回True 或 False
tags = soup.find_all(lambda tag: len(tag.attrs) == 2)
print(tags)

2.6 html解析库

lxml: http://lxml.de/

html.parser:https://docs.python.org/3/library/html.parser.html

相关文章
|
2月前
|
运维 监控 数据可视化
Python 网络请求架构——统一 SOCKS5 接入与配置管理
通过统一接入端点与标准化认证,集中管理配置、连接策略及监控,实现跨技术栈的一致性网络出口,提升系统稳定性、可维护性与可观测性。
|
5月前
|
机器学习/深度学习 算法 量子技术
GQNN框架:让Python开发者轻松构建量子神经网络
为降低量子神经网络的研发门槛并提升其实用性,本文介绍一个名为GQNN(Generalized Quantum Neural Network)的Python开发框架。
133 4
GQNN框架:让Python开发者轻松构建量子神经网络
|
5月前
|
数据采集 Web App开发 数据可视化
Python爬虫分析B站番剧播放量趋势:从数据采集到可视化分析
Python爬虫分析B站番剧播放量趋势:从数据采集到可视化分析b
|
4月前
|
机器学习/深度学习 算法 安全
【PSO-LSTM】基于PSO优化LSTM网络的电力负荷预测(Python代码实现)
【PSO-LSTM】基于PSO优化LSTM网络的电力负荷预测(Python代码实现)
259 0
|
5月前
|
数据采集 数据可视化 搜索推荐
Python数据分析全流程指南:从数据采集到可视化呈现的实战解析
在数字化转型中,数据分析成为企业决策核心,而Python凭借其强大生态和简洁语法成为首选工具。本文通过实战案例详解数据分析全流程,涵盖数据采集、清洗、探索、建模、可视化及自动化部署,帮助读者掌握从数据到业务价值的完整技能链。
651 0
|
2月前
|
机器学习/深度学习 大数据 关系型数据库
基于python大数据的青少年网络使用情况分析及预测系统
本研究基于Python大数据技术,构建青少年网络行为分析系统,旨在破解现有防沉迷模式下用户画像模糊、预警滞后等难题。通过整合多平台亿级数据,运用机器学习实现精准行为预测与实时干预,推动数字治理向“数据驱动”转型,为家庭、学校及政府提供科学决策支持,助力青少年健康上网。
|
3月前
|
JavaScript Java 大数据
基于python的网络课程在线学习交流系统
本研究聚焦网络课程在线学习交流系统,从社会、技术、教育三方面探讨其发展背景与意义。系统借助Java、Spring Boot、MySQL、Vue等技术实现,融合云计算、大数据与人工智能,推动教育公平与教学模式创新,具有重要理论价值与实践意义。
|
2月前
|
数据采集 自然语言处理 数据可视化
Python爬取B站视频评论区情感分析:从数据采集到价值挖掘
B站作为年轻人聚集地,评论蕴含丰富情感与趋势。本文详解如何用Python爬取评论,结合SnowNLP与jieba进行中文情感分析,并通过可视化挖掘用户情绪、消费意愿与内容反馈,助力精准运营与决策。
565 0
|
4月前
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
288 18
|
3月前
|
机器学习/深度学习 算法 PyTorch
【Pytorch框架搭建神经网络】基于DQN算法、优先级采样的DQN算法、DQN + 人工势场的避障控制研究(Python代码实现)
【Pytorch框架搭建神经网络】基于DQN算法、优先级采样的DQN算法、DQN + 人工势场的避障控制研究(Python代码实现)
107 1

热门文章

最新文章

推荐镜像

更多