標籤:from request get sel href other int 擷取網頁 text
import requestsnewsUrl =‘http://news.sina.com.cn/china/‘res = requests.get(newsUrl)res.encoding =‘utf-8’pintprint(res.text)//然後通過DOM Tree來剖析網頁元素 from bs4 import BeautifulSouphtml_sample =‘\<html>\<body>\<h1 id="title">this is h1</h1>\<a class="link" href="fdfdfdfd">this is a link</a>\<a class="link" href="fdfdfdfd">this is another link</a>\</body>\</html>‘‘‘‘html.parser 解析器 ,不寫的話會發出警告‘‘‘soup = BeautifulSoup(html_sample,‘html.parser’)print(soup.text)#找出所有含特定標籤的HTML元素 #1: 使用select 找出含有h1標籤的元素header = soup.select(‘h1’)print(header)print(header[0].text ) #第0個標籤中的文字 #2: 使用select找出含有a標籤的元素alink = soup.select(‘a’)print(alink)for link in alink:#print(link)print(link.text)#取得含有特定CSS屬性的元素#1使用select找出所有id為title的元素(id前需加#) aTitle = soup.select(‘#title‘)print(aTitle)#2使用select找出所有class為link的元素(class前需要加.)for mylink in soup.select(‘.link‘):print(mylink)#取得所有a標籤內的連結#使用select找出所有a tag的href連結 ahref = soup.select(‘a‘)for ah in ahref: print(ah[‘href‘])
通過request擷取網頁資訊 通過BeautifulSoup剖析網頁元素