- 爬蟲必備包 – request
from urllib import request
- 獲取數據
def get_data():
url = ' '
#創建request對象url請求頭
headers = { ' user-agent' : ' ' }
req = request.Request(url, headers=headers)
#傳user-agent
response = request.urlopen(req)
if response.getcode()==200: #確認是否成功
data = response.read() #讀取響應的結果
data = str(data,encoding='utf-8') #轉換爲str
#將數據寫入文件中
with open('idnex.html',mode='w',encoding='utf-8') as f:
f.write(data)
- 處理數據
data parse_data():
with open('index.html',mode='r',encoding='utf-8') as f:
html = f.read()
bs = BeautifulSoup(html,'html.parser') #使用解析器
#1.find方法,獲取第一個匹配的標籤
#div = bs.find('div') #找到相應的內容
#print('div') #打印相應的內容
#print(type((div)) #內容否認類型
#2.find_all方法,或取所有匹配的標籤
#metas = bs.find_all('meta') #返回的是所有的集合
#print(metas[0])
#print(bs.find_all(id='hello')) #根據id 獲取的數據,返回集合
#print(bs,find_all(class_='itany')) #根據class 獲取
#3.獲取select()方法,使用CSS選擇器獲取數據
#print(bs.select('#hello'))
#print(bs.select('.itany'))
#print(bs.select('p#world span'))
#print(bs.select('[title]'))
#獲取文本
#print(bs.select('.div')[0].get_text())
#print(bs.find_all('article'))
value = bs.select('#article')[0].get_text(strip=Ture)
#print(len(value))
print(value)
- main函數
if name==‘main’:
parse_data()