通過request獲取網頁資訊 通過BeautifulSoup剖析網頁元素
阿新 • • 發佈:2017-08-21
獲取網頁 alink his odi res req 特定 bsp css屬性
import requests
newsUrl =‘http://news.sina.com.cn/china/‘
res = requests.get(newsUrl)
res.encoding =‘utf-8’
pint
print(res.text)
//然後通過DOM Tree來剖析網頁元素
from bs4 import BeautifulSoup
html_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剖析網頁元素