国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python常用爬蟲代碼總結(jié)方便查詢

2020-02-16 01:21:04
字體:
供稿:網(wǎng)友

beautifulsoup解析頁面

from bs4 import BeautifulSoupsoup = BeautifulSoup(htmltxt, "lxml")# 三種裝載器soup = BeautifulSoup("<a></p>", "html.parser")### 只有起始標(biāo)簽的會自動補全,只有結(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)簽都會自動補全### 結(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)簽的idsoup.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 HTMLParserhtmls = "<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)            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 思茅市| 封开县| 滨海县| 黔西县| 新宾| 渑池县| 本溪市| 成武县| 北安市| 望江县| 广饶县| 绥阳县| 长寿区| 绥江县| 澎湖县| 遵义县| 霞浦县| 石狮市| 海阳市| 湖州市| 百色市| 秦皇岛市| 林周县| 新营市| 普兰店市| 松原市| 通州区| 北京市| 礼泉县| 南充市| 佛冈县| 临朐县| 阿拉善左旗| 文水县| 鄯善县| 新疆| 永德县| 伊春市| 上虞市| 左云县| 庆阳市|