python爬蟲學習(一)及翻車過程

2021-10-23 02:59:41 字數 1447 閱讀 8537

疫情期間在家沒事開始學python爬蟲,本文記錄我的第乙個爬蟲

接下來上**

1.使用urllib

# 匯入urllib庫的urlopen的函式

from urllib.request import urlopen

# 發出請求,獲取html

html = urlopen("")

# 獲取的html內容是位元組,將其轉化成字串

html_text = bytes.decode(html.read())

# 列印html的內容

print(html_text)

2.使用requests

import requests

head = {

s = requests.get("", headers=head)

print(s.text)

二、解析html

**如下:

import requests

#匯入beautifulsoup 用來解析html

from bs4 import beautifulsoup as bf

head = {

s = requests.get("", headers=head)

#print(s.text)

# 解析html

obj = bf(s.content, 'html.parser')

#獲取head標籤下的title標籤

title = obj.head.title

print(title)

大家只需要注意關於解析html的部分就好了

接下來是執行結果

成功了,鼓掌·······謝謝大家

三、注意點和過程中的報錯

在執行的時候大家可能會遇到「no module named 'requests'」這個錯誤,代表你沒有安裝「requests」模組,當然你解析html使用的bs4也有可能沒有安裝,這時候我們怎麼辦呢?安裝就可以了 在命令列輸入「pip install requests」 就可以安裝「requests」模組了,bs4模組的安裝也是一樣的在命令列輸入「pip install bs4」 即可

pip --default-timeout=100 install requests
我是安裝requests出現的問題,大家如果是安裝其他庫出現這個問題只需要修改 install後面的第三方庫名就可以了

這裡我附上幫我解決問題的大神的部落格,他寫了三種方式:

python 爬蟲學習一

爬取目標 為aspx 使用到了 viewstate eventvalidation cookie來驗證。使用beautifulsoup來解析網頁內容。encoding utf 8 from bs4 import beautifulsoup import urllib import urllib2 d...

python爬蟲學習(一)

簡單例子 抓取網頁全部內容後,根據正規表示式,獲取符合條件的字串列表 from urllib import request 正規表示式 import re url 讀取並解碼,針對中文 編碼是encode response request.urlopen url read decode print ...

python爬蟲學習經歷一

感謝csdn 博主 請叫我汪海 1.url的格式由三部分組成 第一部分是協議 或稱為服務方式 第二部分是存有該資源的主機ip位址 有時也包括埠號 第三部分是主機資源的具體位址,如目錄和檔名等。第一部分和第二部分用 符號隔開,第二部分和第三部分用 符號隔開。第一部分和第二部分是不可缺少的,第三部分有時...