Python常用爬蟲代碼總結(jié)方便查詢
beautifulsoup解析頁面
from bs4 import BeautifulSoup soup = BeautifulSoup(htmltxt, "lxml") # 三種裝載器 soup = BeautifulSoup("<a></p>", "html.parser") ### 只有起始標(biāo)簽的會自動補(bǔ)全,只有結(jié)束標(biāo)簽的會自動忽略 ### 結(jié)果為:<a></a> soup = BeautifulSoup("<a></p>", "lxml") ### 結(jié)果為:<html><body><a></a></body></html> soup = BeautifulSoup("<a></p>", "html5lib") ### html5lib則出現(xiàn)一般的標(biāo)簽都會自動補(bǔ)全 ### 結(jié)果為:<html><head></head><body><a><p></p></a></body></html> # 根據(jù)標(biāo)簽名、id、class、屬性等查找標(biāo)簽 ### 根據(jù)class、id、以及屬性alog-action的值和標(biāo)簽類別查詢 soup.find("a",class_="title",id="t1",attrs={"alog-action": "qb-ask-uname"})) ### 查詢標(biāo)簽內(nèi)某屬性的值 pubtime = soup.find("meta",attrs={"itemprop":"datePublished"}).attrs['content'] ### 獲取所有class為title的標(biāo)簽 for i in soup.find_all(class_="title"): print(i.get_text()) ### 獲取特定數(shù)量的class為title的標(biāo)簽 for i in soup.find_all(class_="title",limit = 2): print(i.get_text()) ### 獲取文本內(nèi)容時可以指定不同標(biāo)簽之間的分隔符,也可以選擇是否去掉前后的空白。 soup = BeautifulSoup('<p class="title" id="p1"><b> The Dormouses story </b></p><p class="title" id="p1"><b>The Dormouses story</b></p>', "html5lib") soup.find(class_="title").get_text("|", strip=True) #結(jié)果為:The Dormouses story|The Dormouses story ### 獲取class為title的p標(biāo)簽的id soup.find(class_="title").get("id") ### 對class名稱正則: soup.find_all(class_=re.compile("tit")) ### recursive參數(shù),recursive=False時,只find當(dāng)前標(biāo)簽的第一級子標(biāo)簽的數(shù)據(jù) soup = BeautifulSoup('<html><head><title>abc','lxml') soup.html.find_all("title", recursive=False)
unicode編碼轉(zhuǎn)中文
content = "\u65f6\u75c7\u5b85" content = content.encode("utf8","ignore").decode('unicode_escape')
url encode的解碼與解碼
from urllib import parse # 編碼 x = "中國你好" y = parse.quote(x) print(y) # 解碼 x = parse.unquote(y) print(x)
html轉(zhuǎn)義字符的解碼
from html.parser import HTMLParser htmls = "<div><p>" txt = HTMLParser().unescape(htmls) print(txt) . # 輸出<div><p>
base64的編碼與解碼
import base64 # 編碼 content = "測試轉(zhuǎn)碼文本123" contents_base64 = base64.b64encode(content.encode('utf-8','ignore')).decode("utf-8") # 解碼 contents = base64.b64decode(contents_base64)
過濾emoji表情
def filter_emoji(desstr,restr=''): try: co = re.compile(u'[\U00010000-\U0010ffff]') except re.error: co = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]') return co.sub(restr, desstr)
完全過濾script和style標(biāo)簽
import requests from bs4 import BeautifulSoup soup = BeautifulSoup(htmls, "lxml") for script in soup(["script", "style"]): script.extract() print(soup)
過濾html的標(biāo)簽,但保留標(biāo)簽里的內(nèi)容
import re htmls = "<p>abc</p>" dr = re.compile(r'<[^>]+>',re.S) htmls2 = dr.sub('',htmls) print(htmls2) #abc 正則提取內(nèi)容(一般處理json) rollback({ "response": { "code": "0", "msg": "Success", "dext": "" }, "data": { "count": 3, "page": 1, "article_info": [{ "title": "“小庫里”:適應(yīng)比賽是首要任務(wù) 投籃終會找到節(jié)奏", "url": "http:\/\/sports.qq.com\/a\/20180704\/035378.htm", "time": "2018-07-04 16:58:36", "column": "NBA", "img": "", "desc": "" }, { "title": "首鋼體育助力國家冰球集訓(xùn)隊(duì) 中國冰球聯(lián)賽年底啟動", "url": "http:\/\/sports.qq.com\/a\/20180704\/034698.htm", "time": "2018-07-04 16:34:44", "column": "綜合體育", "img": "", "desc": "" }...] } }) import re # 提取這個json中的每條新聞的title、url # (.*?)為要提取的內(nèi)容,可以在正則字符串中加入.*?表示中間省略若干字符 reg_str = r'"title":"(.*?)",.*?"url":"(.*?)"' pattern = re.compile(reg_str,re.DOTALL) items = re.findall(pattern,htmls) for i in items: tilte = i[0] url = i[1]
時間操作
# 獲取當(dāng)前日期 today = datetime.date.today() print(today) #2018-07-05 # 獲取當(dāng)前時間并格式化 time_now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) print(time_now) #2018-07-05 14:20:55 # 對時間戳格式化 a = 1502691655 time_a = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(a))) print(time_a) #2017-08-14 14:20:55 # 字符串轉(zhuǎn)為datetime類型 str = "2018-07-01 00:00:00" datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S") # 將時間轉(zhuǎn)化為時間戳 time_line = "2018-07-16 10:38:50" time_tuple = time.strptime(time_line, "%Y-%m-%d %H:%M:%S") time_line2 = int(time.mktime(time_tuple)) # 明天的日期 today = datetime.date.today() tomorrow = today + datetime.timedelta(days=1) print(tomorrow) #2018-07-06 # 三天前的時間 today = datetime.datetime.today() tomorrow = today + datetime.timedelta(days=-3) print(tomorrow) #2018-07-02 13:37:00.107703 # 計算時間差 start = "2018-07-03 00:00:00" time_now = datetime.datetime.now() b = datetime.datetime.strptime(start,'%Y-%m-%d %H:%M:%S') minutes = (time_now-b).seconds/60 days = (time_now-b).days all_minutes = days*24*60+minutes print(minutes) #821.7666666666667 print(days) #2 print(all_minutes) #3701.7666666666664
數(shù)據(jù)庫操作
import pymysql conn = pymysql.connect(host='10.0.8.81', port=3306, user='root', passwd='root',db='xxx', charset='utf8') cur = conn.cursor() insert_sql = "insert into tbl_name(id,name,age) values(%s,%s,%s) id = 1 name = "like" age = 26 data_list = [] data = (id,name,age) # 單條插入 cur.execute(insert_sql,data) conn.commit() # 批量插入 data_list.append(data) cur.executemany(insert_sql,data_list) conn.commit() #特殊字符處理(name中含有特殊字符) data = (id,pymysql.escape_string(name),age) #更新 update_sql = "update tbl_name set content = '%s' where id = "+str(id) cur.execute(update_sql%(pymysql.escape_string(content))) conn.commit() #批量更新 update_sql = "UPDATE tbl_recieve SET content = %s ,title = %s , is_spider = %s WHERE id = %s" update_data = (contents,title,is_spider,one_new[0]) update_data_list.append(update_data) if len(update_data_list) > 500: try: cur.executemany(update_sql,update_data_list) conn.commit()
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
- Nginx服務(wù)器屏蔽與禁止屏蔽網(wǎng)絡(luò)爬蟲的方法
- Python爬蟲beautifulsoup4常用的解析方法總結(jié)
- Python 通過requests實(shí)現(xiàn)騰訊新聞抓取爬蟲的方法
- Python3爬蟲之自動查詢天氣并實(shí)現(xiàn)語音播報
- Python爬蟲之UserAgent的使用實(shí)例
- 基于node.js實(shí)現(xiàn)爬蟲的講解
- 淺談Scrapy網(wǎng)絡(luò)爬蟲框架的工作原理和數(shù)據(jù)采集
- 用Electron寫個帶界面的nodejs爬蟲的實(shí)現(xiàn)方法
- 通過python爬蟲賺錢的方法
- 如何禁止網(wǎng)站內(nèi)容被搜索引擎收錄的幾種方法講解
相關(guān)文章
Python3.7+tkinter實(shí)現(xiàn)查詢界面功能
這篇文章主要介紹了Python3.7+tkinter實(shí)現(xiàn)查詢界面功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12Python對比校驗(yàn)神器deepdiff庫使用詳解
deepdiff模塊常用來校驗(yàn)兩個對象是否一致,包含3個常用類,DeepDiff,DeepSearch和DeepHash,其中DeepDiff最常用,可以對字典,可迭代對象,字符串等進(jìn)行對比,使用遞歸地查找所有差異,本文給大家講解Python對比校驗(yàn)神器deepdiff庫,感興趣的朋友一起看看吧2023-04-04Python實(shí)現(xiàn)實(shí)時跟隨微信窗口移動的GUI界面
Python寫一些簡單的GUI界面也是非常簡單的,并且Python有著豐富的庫,這些庫可以很方便我們?nèi)ゲ僮鱓indows系統(tǒng)。本文就來用Python編寫一個實(shí)時跟隨微信窗口移動的GUI界面吧2023-04-04詳解Django的model查詢操作與查詢性能優(yōu)化
這篇文章主要介紹了詳解Django的model查詢操作與查詢性能優(yōu)化,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10詳解Python利用APScheduler框架實(shí)現(xiàn)定時任務(wù)
在做一些python工具的時候,常常會碰到定時器問題,總覺著使用threading.timer或者schedule模塊非常不優(yōu)雅。所以本文將利用APScheduler框架實(shí)現(xiàn)定時任務(wù),需要的可以參考一下2022-03-03pytorch中獲取模型input/output shape實(shí)例
今天小編就為大家分享一篇pytorch中獲取模型input/output shape實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12Keras使用預(yù)訓(xùn)練模型遷移學(xué)習(xí)單通道灰度圖像詳解
這篇文章主要介紹了Keras使用預(yù)訓(xùn)練模型遷移學(xué)習(xí)單通道灰度圖像詳解,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02