python爬虫2:按html标签提取信息和中文域名处理(BeautifulSoup用法初步)

复制代码
 1 #!/usr/bin/env python  
 2 # -*- coding: utf-8 -*-  
 3 # python3
 4 import string
 5 import urllib
 6 from urllib import request
 7 from bs4 import BeautifulSoup
 8 
 9 url="https://ne0matrix.com/2020/01/08/伊朗,赢了"
10 # 有中文的url,直接urlopen会出错,需要quote处理一下。
safe=参数表示不需要被处理的字符,默认为/。现在设为string.printable表示非中文的不需要转换。 11 12 url_quote=urllib.parse.quote(url,safe=string.printable) 13 # quote的逆向操作unquote: 14 # url_unquote=urllib.parse.unquote(url_quote 15 print (url_quote) 16 17 page_read=request.urlopen(url_quote).read() 18 page_decode=page_read.decode('utf-8') 19 with open ('output.html','w')as f: 20 f.write(page_decode) 21 22 with open ('output.html','r')as f: 23 alltext=f.read() 24 bsobj=BeautifulSoup(alltext,'html.parser') 25 # 如果不加html.parser则使用默认的lxmlparser,会有警告,但不影响使用 26 27 print (bsobj.title) 28 # 获取标题<title>... 29 print (bsobj.title.get_text()) 30 # get_text()获取纯文字的标题 31 date=bsobj.find('p',{'class':'mt-3'}).get_text() 32 print (date.strip()) 33 # strip()去掉前后空格 34 count=bsobj.find('span',{'class':'post-count'}) 35 print(count.get_text().strip()) 36 text=bsobj.find('div',{'class':'markdown-body'}) 37 print(text.get_text()) 38 # 查找正文
复制代码

 

posted @   cityfckr  阅读(333)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示