1.利用requests.get(url)获取网页页面的html文件
import requests newsurl='http://news.gzcc.cn/html/xiaoyuanxinwen/' res = requests.get(newsurl) #返回response对象 res.encoding='utf-8' print(res.text)
结果截图
2.利用BeautifulSoup的HTML解析器,生成结构树
from bs4 import BeautifulSoup soup = BeautifulSoup(res.text,'html.parser')
3.找出特定标签的html元素
print(soup.body.div.div) print(soup.body.div.div.contents) print(soup.head) print(soup.head.text) print(soup.select('li'))
4.取得含有特定CSS属性的元素
print(soup.select('.container')) print(soup.select('#top'))
取出h1标签的文本
print(soup.body.h1.text)
取出a标签的链接
print(soup.body.a.attrs['href']) print(soup.body.li.a.attrs['href'])
取出所有li标签的所有内容
print(soup.body.li.text) print(soup.body.li.contents)
取出一条新闻的标题、链接、发布时间、来源
s0=soup.select('.news-list-title')[0].text s3=soup.body.li.a.attrs['href'] s1=soup.select('.news-list-info')[0].contents[0].text s2=soup.select('.news-list-info')[0].contents[1].text