python3爬取1000个百度百科页面(一)

一、基本概念

       爬虫:一段自动抓取互联网信息的程序

二、简单爬虫架构

       

1、URL管理器:管理已经爬取和未曾爬取的url,防止重复、循环抓取

       python中set可以直接去除重复元素  

      

2、网页下载器:将网页下载到本地,urllib2,request,

3、网页解析器:从网页中提取有价值的数据的工具,可以解析网页含有的url和数据,方式有正则表达式、html.parser、BeautifulSoup等

结构化解析:将网页解析成DOM(Document Object Mode)树

                                      

三、使用urllib下载网页的三种方法

import urllib.request
import http.cookiejar

url = "http://www.baidu.com"

# 最简洁的方法
print("第一种方法")
# 返回网页内容
response1 = urllib.request.urlopen(url)
# getcode()返回状态码,返回200,则网页下载成功,否则失败,
print(response1.getcode())
# read()方法来获取下载的内容
print(len(response1.read()))

print("第二种方法")
request = urllib.request.Request(url)
# 把爬虫伪装成Mozilla浏览器
request.add_header("user-agent","Mozilla/5.0")
response2 = urllib.request.urlopen(url)
print(response2.getcode())
print(response2.read())

# 添加特殊情景处理器,HTTPCookieProcessor、ProxyHandler等
print("第三种方法")
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
# 安装这个opener
urllib.request.install_opener(opener) 
response3 = urllib.request.urlopen(url)
print(response3.getcode())
print(cj)
print(len(response3.read()))

注:

       1、在python3中,在python3.3后urllib2已经不能再用,只能用urllib.request来代替,

       2、在python3中,cookie要使用http.cookiejar,而不是cookie

四、BeautifuSoup模块解析

       BeautifuSoup文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/

       1、将网页下载成DOM树

       2、搜索各种节点find_all(搜索所有满足条件的节点),find(只搜索第一个节点)。参数都一样

            然后可以访问节点的名称、属性、文字,也可以按照节点名称、属性、文字访问,

     

# bs4模块 解析字符串
from bs4 import BeautifulSoup
import re

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

# 创建BS对象
# html.parse是解析器
soup = BeautifulSoup(html_doc,'html.parser',from_encoding='utf-8')  
print("获取所有的链接")

# 查找所有标签为'a'的节点
links = soup.find_all('a')
for link in links:
    print(link.name,link['href'],link.get_text())
    
print("获取lacie的链接")
link_node = soup.find('a',href = "http://example.com/lacie")
print(link_node.name,link_node['href'],link_node.get_text())

# 正则匹配(模糊匹配)
print("正则匹配")
# 字母r,正则表达式出现反斜杠的话,我们只需要写一个
link_node = soup.find('a',href = re.compile(r"ill"))     
print(link_node.name,link_node['href'],link_node.get_text())

# 获取P段落文字
# class是python关键字,所以加下划线
print("获取P段落文字")
p_node = soup.find('p',class_ = "title") 
print(p_node.name,p_node.get_text())

猜你喜欢

转载自blog.csdn.net/bailixuance/article/details/83006025
今日推荐