国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

python爬蟲beautifulsoup解析html方法

瀏覽:23日期:2022-07-03 08:08:36

用BeautifulSoup 解析html和xml字符串

python爬蟲beautifulsoup解析html方法

實例:

#!/usr/bin/python# -*- coding: UTF-8 -*-from bs4 import BeautifulSoupimport re#待分析字符串html_doc = '''<html><head> <title>The Dormouse’s story</title></head><body><p class='title aq'> <b> The Dormouse’s story </b></p><p class='story'>Once upon a time there were three little sisters; and their names were <a rel='external nofollow' id='link1'>Elsie</a>, <a rel='external nofollow' id='link2'>Lacie</a> and <a rel='external nofollow' id='link3'>Tillie</a>; and they lived at the bottom of a well.</p><p class='story'>...</p>'''# html字符串創建BeautifulSoup對象soup = BeautifulSoup(html_doc, ’html.parser’, from_encoding=’utf-8’)#輸出第一個 title 標簽print soup.title#輸出第一個 title 標簽的標簽名稱print soup.title.name#輸出第一個 title 標簽的包含內容print soup.title.string#輸出第一個 title 標簽的父標簽的標簽名稱print soup.title.parent.name#輸出第一個 p 標簽print soup.p#輸出第一個 p 標簽的 class 屬性內容print soup.p[’class’]#輸出第一個 a 標簽的 href 屬性內容print soup.a[’href’]’’’soup的屬性可以被添加,刪除或修改. 再說一次, soup的屬性操作方法與字典一樣’’’#修改第一個 a 標簽的href屬性為 http://www.baidu.com/soup.a[’href’] = ’http://www.baidu.com/’#給第一個 a 標簽添加 name 屬性soup.a[’name’] = u’百度’#刪除第一個 a 標簽的 class 屬性為del soup.a[’class’]##輸出第一個 p 標簽的所有子節點print soup.p.contents#輸出第一個 a 標簽print soup.a#輸出所有的 a 標簽,以列表形式顯示print soup.find_all(’a’)#輸出第一個 id 屬性等于 link3 的 a 標簽print soup.find(id='link3')#獲取所有文字內容print(soup.get_text())#輸出第一個 a 標簽的所有屬性信息print soup.a.attrsfor link in soup.find_all(’a’): #獲取 link 的 href 屬性內容 print(link.get(’href’))#對soup.p的子節點進行循環輸出 for child in soup.p.children: print(child)#正則匹配,名字中帶有b的標簽for tag in soup.find_all(re.compile('b')): print(tag.name)

爬蟲設計思路:

python爬蟲beautifulsoup解析html方法

詳細手冊:

https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

到此這篇關于python爬蟲beautifulsoup解析html方法 的文章就介紹到這了,更多相關beautifulsoup解析html內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 故城县| 长丰县| 双峰县| 竹北市| 博白县| 定襄县| 遂平县| 上杭县| 嘉禾县| 上林县| 虞城县| 霍山县| 景东| 天台县| 砚山县| 延吉市| 阳城县| 洱源县| 定兴县| 罗山县| 五莲县| 冷水江市| 壤塘县| 中西区| 延寿县| 民丰县| 马尔康县| 宁晋县| 海淀区| 威远县| 开平市| 哈巴河县| 双辽市| 沙坪坝区| 安陆市| 延安市| 英吉沙县| 河津市| 沂南县| 襄汾县| 正镶白旗|