0.能够新建一个用于练习的html文件,在浏览器中打开。html
1.利用requests.get(url)获取网页页面的html文件浏览器
import requestsurl
newsurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'spa
res = requests.get(newsurl) #返回response对象code
res.encoding='utf-8'htm
2.利用BeautifulSoup的HTML解析器,生成结构树对象
from bs4 import BeautifulSoupblog
soup = BeautifulSoup(res.text,'html.parser')utf-8
3.找出特定标签的html元素字符串
soup.p #标签名,返回第一个
soup.head
soup.p.name #字符串
soup.p. attrs #字典,标签的全部属性
soup.p. contents # 列表,全部子标签
soup.p.text #字符串
soup.p.string
soup.select(‘li')
4.取得含有特定CSS属性的元素
soup.select('#p1Node')
soup.select('.news-list-title')
5.练习:
取出h1标签的文本
取出a标签的连接
取出全部li标签的全部内容
取出第2个li标签的a标签的第3个div标签的属性
取出一条新闻的标题、连接、发布时间、来源
# -*- coding:utf-8 -*- import requests from bs4 import BeautifulSoup res = requests.get('http://localhost:63342/demo/demo.html?_ijt=ckuj5j0gqtro8l1rnki5ik6j7f') res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') # 取出h1标签的文本 print(soup.h1.text) # 取出a标签的连接 print(soup.a['href']) # 取出全部li标签的全部内容 for i in soup.select('li'): print(i) # 取出第2个li标签的a标签的第3个div标签的属性 print(soup.select('li')[1].a.select('div')[2].attrs) # 取出一条新闻的标题、连接、发布时间、来源 print('标题:'+soup.select('.news-list-title')[0].text) print('连接:'+soup.select('a')[2]['href']) print('发布时间:'+soup.select('.news-list-info')[0].span.text) print('来源:'+soup.select('.news-list-info')[0].select('span')[1].text)