爬虫5-BeautifulSoup模块简解
生活随笔
收集整理的這篇文章主要介紹了
爬虫5-BeautifulSoup模块简解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、html標記語言了解
<html> <meta http-equiv="Content-Type"content="text/html;charset=utf-8"> <h1>我的祖國</h1> <h1 align="center">我的祖國</h1> # h1 標簽 # align 屬性 # center 屬性值 <標簽 屬性="屬性值">被標記的內容</標簽> <img src="xxx.jpg"/> <a href="http://www.baidu.com">百度</a> </html>2、BeautifulSoup模塊介紹
# 1.拿到頁面源代碼 # 2.使用bs4進行解析 拿到數據 import requests from bs4 import BeautifulSoup import csv url = "http://www.xinfadi.com.cn/marketanalysis/0/list/1.shtml" resp = requests.get(url)# # 解析數據 # # 1.把頁面源代碼交給BeautifulSoup進行處理 生成bs對象 # # page = BeautifulSoup(resp.text) page = BeautifulSoup(resp.text, "html.parser") # # 2.從bs對象中查找對象 # # find(標簽名,屬性=值) # # find_all(標簽名,屬性=值) table = page.find("table", class_="hq_table") # class 是python中的關鍵字 # # table = page.find("table", attrs={"class": "hq_table"}) #等價于上一行 可以避免class # print(table) # 拿到所有數據行trs = table.find_all("tr") trs = table.find_all("tr")[1:] f = open("菜價.csv", mode="w",encoding='utf-8') csvwriter = csv.writer(f) for tr in trs:tds = tr.find_all("td") # 拿到每行的tdprint(tds)name = tds[0].textlow = tds[1].textaverage = tds[2].texthigh = tds[3].textgui = tds[4].textkind = tds[5].textdate = tds[5].textprint(name, low, average, high, gui, kind, date)csvwriter.writerow([name, low, average, high, gui, kind, date]) f.close() resp.close()總結
以上是生活随笔為你收集整理的爬虫5-BeautifulSoup模块简解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql语句 int(11)含义误区
- 下一篇: python并发编程6-协程