介紹BeautifulSoup庫的使用,並爬取股票代碼

代碼如下:

#本代碼介紹BeautifulSoup庫的使用,並爬取股票代碼
#1、導入相應的模塊
import requests
from bs4 import BeautifulSoup
#2、對網頁進行get請求
url="http://quote.eastmoney.com/center/gridlist.html#hs_a_board" #設置東方財富網個股行情中心為爬取網站的地址
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0"} #設置請求頭
response=requests.get(url,headers=headers) # 對網頁url進行get請求
response.encoding="utf-8" #設置編碼格式為utf-8
html=response.text
#3、解析網站並打印相應內容
soup=BeautifulSoup(html,"html.parser") #設置html.parser為解析器
print("格式化後的html代碼:",soup.prettify())
print("標題信息:",soup.title.string)
print("網頁的head標籤:",soup.head)
print("網頁的meta標籤:",soup.meta)
print("網頁的第一個a標籤屬性href的值:",soup.a.attrs["href"])
print("網頁的第一個a標籤內部的內容:",soup.a.string)
print("打印a標籤的父節點:",soup.a.parent)
print("打印a標籤的祖先節點:",soup.a.parents)
print("網頁的第一個a標籤屬性下一個的值:",list(enumerate(soup.a.previous_siblings)))

運行結果如下圖所示:

介紹BeautifulSoup庫的使用,並爬取股票代碼


分享到:


相關文章: