python爬取網頁內容的簡單程式

2021-10-08 02:45:45 字數 1272 閱讀 9623

'''

1.目標**:

2.分析目標網頁的標籤

3.熟悉標籤結構

4.匯入第三方庫

5.**實現

'''import requests

from bs4 import beautifulsoup

#要爬取的**

url =

''#1.發起請求

response = requests.

get(url=url)

#2.判斷是否請求成功,根據狀態碼判斷

print

('狀態碼'

,response.status_code)

#3.設定與請求的頁面的相同的編碼, 預設瀏覽器 iso

-8859-1

response.encoding =

'gbk'

#4.解析請求的結構

html = response.text

#5.解析結構

soup =

beautifulsoup

(html,

'lxml'

)#6.利用解析的例項化物件進行標籤內容的獲取

bs_text = soup.

find_all

('div'

, class_=

'showtxt'

)texts = bs_text[0]

.text

#print

(texts)

#7.去除空格 或者 空行

texts = texts.

replace

("'\xa0'"

,'\n\n'

)file =

open

('超跑.txt'

,'w'

,encoding=

'utf-8'

,newline='')

#9.寫入

file.

write

(texts)

#10.關閉

file.

close()

print

('over!'

)

對網頁分析

使用火狐或者谷歌 按f12

檢視如下

Python爬取網頁內容

其時序圖如圖所示。給定乙個要訪問的url,獲取這個html及內容,遍歷html中的某一類鏈結,如a標籤的href屬性,從這些鏈結中繼續訪問相應的html頁面,然後獲取這些html的固定標籤的內容,如果需要多個標籤內容,可以通過字串拼接,最後通過正規表示式刪除所有的標籤,最後將其中的內容寫入.txt檔...

靜態網頁內容爬取(python)

以 漏洞掃瞄為例 from bs4 import beautifulsoup from urllib.request import urlopen import pymysql as mysqldb import re import os 插入資料 def insertdata lis cursor...

python lxml爬取網頁內容

from lxml import etree import requests url response requests.get url text response.text html etree.html text 先獲取到這個頁面的html,對了,這裡還用到了xpath來選擇節點,具體用法請參考...