第14.9节 Python中使用urllib.request+BeautifulSoup获取url访问的基本信息

29 篇文章 23 订阅

利用urllib.request读取url文档的内容并使用BeautifulSoup解析后,可以通过一些基本的BeautifulSoup对象输出html文档的基本信息。以博文《第14.6节 使用Python urllib.request模拟浏览器访问网页的实现代码》访问为例,读取和解析代码如下:

>>> from bs4 import BeautifulSoup
>>> import urllib.request
>>> def getURLinf(url): 
    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'}
    req = urllib.request.Request(url=url,headers=header)
    resp = urllib.request.urlopen(req,timeout=5)
    html = resp.read().decode()
  
    soup = BeautifulSoup(html,'lxml')
    return (soup,req,resp) 
>>>  soup,req ,resp  = getURLinf(r'https://blog.csdn.net/LaoYuanPython/article/details/100629947')

可获取的基本信息包括:
1、 文档标题

>>> soup.title
<title>第14.6节 使用Python urllib.request模拟浏览器访问网页的实现代码 - 老猿Python - CSDN博客</title>

2、 文档是否为xml文档

>>> soup.is_xml
False

3、 文档的url地址

>>> req.full_url
'https://blog.csdn.net/LaoYuanPython/article/details/100629947'
>>> resp.geturl()
'https://blog.csdn.net/LaoYuanPython/article/details/100629947'
>>> resp.url
'https://blog.csdn.net/LaoYuanPython/article/details/100629947'
>>>

4、 文档所在的主机

>>> req.host
'blog.csdn.net'

5、 请求头的信息

>>> req.header_items()
[('Host', 'blog.csdn.net'), ('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36')]
>>>

6、 响应状态码

>>> resp.getcode()
200
>>>

7、 响应http报文头信息

>>> resp.headers.items()
[('Date', 'Sun, 08 Sep 2019 15:07:12 GMT'), ('Content-Type', 'text/html; charset=UTF-8'), ('Transfer-Encoding', 'chunked'), ('Connection', 'close'), ('Set-Cookie', 'acw_tc=2760828215679552322374611eb7315abdcfe4ee6f7af5d157db5621c4267d;path=/;HttpOnly;Max-Age=2678401'), ('Server', 'openresty'), ('Vary', 'Accept-Encoding'), ('Set-Cookie', 'uuid_tt_dd=10_19729129290-1567955232238-614052; Expires=Thu, 01 Jan 2025 00:00:00 GMT; Path=/; Domain=.csdn.net;'), ('Set-Cookie', 'dc_session_id=10_1567955232238.557324; Expires=Thu, 01 Jan 2025 00:00:00 GMT; Path=/; Domain=.csdn.net;'), ('Vary', 'Accept-Encoding'), ('Strict-Transport-Security', 'max-age=86400')]
>>>

本节介绍了使用urllib.request读取url文档的内容并使用BeautifulSoup解析后可以很方便的获取的一些url访问的基本信息,通过这些信息可以对本次访问提供一些概要的信息。

老猿Python,跟老猿学Python!
博客地址:https://blog.csdn.net/LaoYuanPython

老猿Python博客文章目录:https://blog.csdn.net/LaoYuanPython/article/details/98245036
请大家多多支持,点赞、评论和加关注!谢谢!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LaoYuanPython

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值