利用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'http://iyenn.com/rec/324980.html')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
可获取的基本信息包括:
1、 文档标题
>>> soup.title
第14.6节 使用Python urllib.request模拟浏览器访问网页的实现代码 - 老猿Python - CSDN博客
- 1
- 2
2、 文档是否为xml文档
>>> soup.is_xml
False
- 1
- 2
3、 文档的url地址
>>> req.full_url
'http://iyenn.com/rec/324980.html'
>>> resp.geturl()
'http://iyenn.com/rec/324980.html'
>>> resp.url
'http://iyenn.com/rec/324980.html'
>>>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
4、 文档所在的主机
>>> req.host
'blog.csdn.net'
- 1
- 2
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')]
>>>
- 1
- 2
- 3
6、 响应状态码
>>> resp.getcode()
200
>>>
- 1
- 2
- 3
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')]
>>>
- 1
- 2
- 3
本节介绍了使用urllib.request读取url文档的内容并使用BeautifulSoup解析后可以很方便的获取的一些url访问的基本信息,通过这些信息可以对本次访问提供一些概要的信息。
老猿Python,跟老猿学Python!
博客地址:http://iyenn.com/index/link?url=https://blog.csdn.net/LaoYuanPython
老猿Python博客文章目录:http://iyenn.com/rec/324322.html
请大家多多支持,点赞、评论和加关注!谢谢!
文章知识点与官方知识档案匹配,可进一步学习相关知识
Python入门技能树网络爬虫Beautiful Soup333550 人正在系统学习中

老猿Python
微信公众号
专注Python相关语言、图像音视频处理、AI


评论记录:
回复评论: