1. 程式人生 > >python 爬蟲之BeautifulSoup 庫的基本使用

python 爬蟲之BeautifulSoup 庫的基本使用

rip data lin value 訪問 pytho 輕松 register tex

import urllib2
url = ‘http://www.someserver.com/cgi-bin/register.cgi‘
values = {}
values[‘name‘] = ‘Michael Foord‘
values[‘location‘] = ‘Northampton‘
values[‘language‘] = ‘Python‘

data = urllib.urlencode(values) #數據進行編碼生成get方式的請求字段
req = urllib2.Request(url,data) #作為data參數傳遞到Request對象中 POST方式訪問
response = urllib2.urlopen(req) 返回一個類文件對象

the_page = response.read()
soup = BeautifulSoup(the_page,"html.parser") 通過類文件the_page 創建beautifulsoup對象,soup的內容就是頁面的源碼內容
構造好BeautifulSoup對象後,借助find()和find_all()這兩個函數,可以通過標簽的不同屬性輕松地把繁多的html內容過濾為你所想要的
url_name = line.get(‘href‘) 獲取a標簽的url信息
Title = line.get_text().strip() 獲取a標簽的文本內容

python 爬蟲之BeautifulSoup 庫的基本使用