python爬蟲學習

2021-08-13 08:28:08 字數 1024 閱讀 1629

一、beautiful soup庫

1、引用

from bs4 import beautifulsoup

from bs4 import beautifulsoup

soup = beautifulsoup('data

', 'html.parser')

2、beautifulsoup類的基本元素

tag 標籤,最基本的資訊組織單元,分別用<>和

for child in soup.body.children:

print(child)

for child in soup.body.descendants:

print(child)

遍歷兒子節點

遍歷子孫節點

**注意!!! 下行遍歷需要 增加乙個 if isinstance(child, bs4.element.tag):

篩掉 \n換行符 等其他不是標籤的元素**

5、上行遍歷

.parent

.parents

6、平行遍歷

.next_sibling 返回按照html文字順序的下乙個平行節點標籤

.previous_sibling 返回按照html文字順序的上乙個平行節點標籤

.next_siblings 迭代型別,返回按照html文字順序的後續所有平行節點標籤

.previous_siblings 迭代型別,返回按照html文字順序的前續所有平行節點標籤

標籤樹的平行遍歷

for sibling in soup.a.next_sibling:

print(sibling)

for sibling in soup.a.previous_sibling:

print(sibling)

遍歷後續節點

遍歷前續節點

注意!!!平行遍歷是遍歷節點,所以包括字串等

7、bs4的prettify()方法

Python爬蟲學習

最近由於 需要,用python寫了爬蟲爬取資料。在這個過程中,認識到學習一門語言最好的辦法是動手,別無技巧。在動手程式設計的過程中,遇到了很多意想不到的問題,當然也學習了很多書本上不會講述的知識,感覺這才是真正的學習知識。在這個過程中,遇到的乙個問題讓我花費了很久時間,留下了很深的印象。擔心會隨著時...

Python學習 爬蟲

在搜尋python知識的時候一直看到爬蟲相關知識,感覺挺好玩的,打算簡單了解一下。1 找到伺服器主機,向伺服器發出乙個請求,伺服器經過解析之後,傳送給使用者的瀏覽器 html js css 等檔案,瀏覽器解析出來,使用者便可以看到形形色色的了。因此,使用者看到的網頁實質是由 html 構成的,爬蟲爬...

python爬蟲學習

例如列印當前時間 from datetime import datetime print datetime.now 或者import datetime print datetime.datetime.now html結構 html head body html head a useful page ...