網絡爬蟲學習(二)
1、BeautifulSoup 基礎操作
上次代碼爲:
from bs4 import BeautifulSoup
html_sample=' \
<html> \
<body> \
<h1 id="title"> Hello World</h1> \
<a href="#" class="link">This is link1</a> \
<a href="# link2" class="link"> This is link2</a> \
</body> \
</html>'
soup=BeautifulSoup(html_sample,'html.parser')
print (soup.text)
(1)找出所有含特定標籤的HTML元素
- 使用select找出含有h1標記的元素
soup=BeautifulSoup(html_sample,'html.parser')
header=soup.select('h1')
print (header)
print (header[0])
print (header[0].text)
- 使用select找出含有a標籤的元素
soup=BeautifulSoup(html_sample,'html.parser') alink=soup.select('a') print (alink) for link in alink: #將標籤分2行打印 #print (link) print (link.text)#取出標籤裏面的內容
(2)取得含有特定CSS屬性的元素
- 使用select找出所有id爲title的元素(id前面需加#)
alink=soup.select('#title') print (alink)
- 使用select找出所有class爲link的元素(class前面需加.)
soup=BeautifulSoup(html_sample) for link in soup.select('.link'): print (link)
(3)取得所有a標籤內的鏈接
- 使用select找出所有a tag的href鏈接
alinks=soup.select('a') for link in alinks: print (link['href'])
示例
a='<a href="#" qoo=123 abc=456> I am a linker</a>'
soup2=BeautifulSoup(a,'html.parser')
print (soup2.select('a'))
print (soup2.select('a')[0]['abc'])#輸出abc後面的值
print (soup2.select('a')[0]['qoo'])#輸出qoo後面的值
2、觀察元素抓取位置
使用檢查工具,可以看到新聞內容上面顯示的“news_item.first-news-item”
其代碼爲:
3、根據不同HTML標籤取得對應的內容
4、完成所有的爬蟲
代碼如下:
import requests
from bs4 import BeautifulSoup
res=requests.get('http://news.sina.com.cn/china/')
res.encoding='utf-8'
soup= BeautifulSoup(res.text,'html.parser')
for news in soup.select('.news-item'):
if len(news.select('h2'))>0:
h2=(news.select('h2')[0].text)
time=(news.select('.time')[0].text)
a=news.select('a')[0]['href']
print (time,h2,a)
結果: