Python 网页下载器和解析器

某教程网 python 爬虫视频 http://www.imooc.com/learn/563有段代码在3.X中有变化。在 3.x 版本中 ,把 2.x 版本的模块 urllib2 合并为 urllib.request 。


视频中原代码:


更改为 3.x 的版本:

# -*- coding: utf-8 -*-  
# python 3.5
# 网页下载器测试

import urllib.request
import http.cookiejar

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

print("第一种方法:最简洁方法")
response1 = urllib.request.urlopen(url) #直接请求
print(response1.getcode()) #网页状态吗,200表示成功
print(len(response1.read())) #网页html内容

print("第二种方法:添加data、http header")
request = urllib.request.Request(url)
request.add_header("user-agent", "Mozilla/5.5") #添加http的header
response2 = urllib.request.urlopen(url) #发送请求获取结果
print(response2.getcode())
print(len(response2.read()))

print("第三种方法:")
cj = http.cookiejar.CookieJar() #创建cookie容器
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) #创建opener
urllib.request.install_opener(opener) #给urllib 安装 opener
response3 = urllib.request.urlopen(url) #使用带有 cookie 的 urllib 访问网页
print(response3.getcode())
print(len(response3.read()))

网页解析测试:

# -*- coding: utf-8 -*-  
# python 3.5
# 网页解析测试

import re
from bs4 import BeautifulSoup

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>
"""

soup = BeautifulSoup(html_doc,'html.parser')
print('获取所有链接')
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('正则匹配')
link_node =  soup.find('a',href=re.compile(r"ill"))
print(link_node.name,link_node['href'],link_node.get_text())

print('获取P段落文字')
p_node =  soup.find('p',class_="title")
print(p_node.name,p_node.get_text())


输出结果:
获取所有链接
a http://example.com/elsie Elsie
a http://example.com/lacie Lacie
a http://example.com/tillie Tillie
获取lacie链接
a http://example.com/lacie Lacie
正则匹配
a http://example.com/tillie Tillie
获取P段落文字
p The Dormouse's story


附上一张简单爬虫框架图:




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值