抓取頁面,提取標題,內容,並插入dbmongo

2021-10-11 18:01:14 字數 2688 閱讀 3411

存在的問題,在多執行緒抓取中,存在大量重複抓取鏈結,待解決

# -*- coding : utf-8 -*-

# ①獲取url源** --② 獲取標題,摘要(11:30~12:30) ③ 插入db資料庫(17:00~18:00) ④ 村環獲取所有鏈結,並插入資料庫(19:30前) ⑤ 處理問題(回家解決並上傳csdn)

self.con_mongo(*article) #這種模式是在函式定義時在某個形參前面加乙個星號,呼叫時按位置匹配不帶星號的形參和實參,多餘的實參都將作為乙個元組的元素儲存到星號對應的形參中。

finally:

self.query.task_done()

def down_source(self,site,retries=3):

try:

r = requests.get(site,headers = self.headers)

except requests.timeout as err:

html = none

if retries > 0 :

self.down_source(site,retries =retries-1)

else:

print(f"載入超時..")

except requests.requestexception as err:

html = none

else:

r.encoding = "utf-8"

html = r.text

return html

@staticmethod

def parsing(res):

doc = etree.html(res) # 將html內容轉化為文件數 格式為title = ''.join(doc.xpath('//h1[@class="article-title"]/a/text()'))

content = doc.xpath('//article[@class="article-content"]')

s1 = etree.tostring(content[0], method='html', encoding='utf-8')

s1 = s1.decode('utf-8')

# 將html編碼轉換為字串表示

article_content = unescape(s1)

# res_content = re.sub(r']*>|]*>','',article_content) # 去除**中的div

res_content = re.sub(r']*>|[\s\s]*

','',article_content).strip() # 去除**中的div

return title,res_content

def get_url(self,res):

doc = etree.html(res)

r_url = doc.xpath('//a/attribute::href')

for s_url in r_url:

url1 = ''.join(re.findall(r'', s_url))

self.query.put(url1)

@staticmethod

def con_mongo(title,content):

collecting.insert_one()

if __name__ == "__main__":

query = queue()

url = ""

query.put(url)

client = mongoclient()

db = client['bdspride'] # 建立/鏈結資料庫

collecting = db['wui6'] # 建立集合

使用phpQuery 抓取HTML 頁面內容

使用phpquery 可以對html 頁面進行類似於jquery 一樣的操作。目的是進行html 資料的抓取,以及對html 檔案內容的補充等操作,完全就類似於jquery 一樣的操作。require once phpquery phpquery.php url html file get cont...

python執行緒抓取頁面簡單內容

用到的基本就是之前提到的執行緒小框架及邏輯 encoding utf 8 import requests from lxml import etree import threading import os class cnbeta object thread 獲取 首頁 def get url se...

CURL抓取頁面時替換頁面內容

其實把抓取下來的頁面用str replace進行替換就可以了 curl.php如下 curl使用 path 1初始化 ch curl init curl setopt ch,curlopt url,path curl setopt ch,curlopt returntransfer,true out...