Python實(shí)現(xiàn)獲取網(wǎng)頁信息并解析
Python爬蟲用到的兩個(gè)主要的庫是:bs4和request,request用于發(fā)起請求,而bs4用于網(wǎng)頁元素解析。
以阮一峰老師的博客為例,每周最喜歡的是科學(xué)愛好者周刊中的“言論”不分,以 科技愛好者周刊(第 253 期)為例,讓我們來看看能不能將言論部分提取出來。
import requests
from bs4 import BeautifulSoup
url = "http://www.ruanyifeng.com/blog/2023/05/weekly-issue-253.html"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
first_tag = soup.find("h2", string="言論")
next_sibling = first_tag.find_next_sibling()
content1 = ""
while next_sibling.name != "h2":
content1 += str(next_sibling.get_text())
# content1 += str(next_sibling)
content1 += "\n\n"
next_sibling = next_sibling.find_next_sibling()
print(content1)
執(zhí)行結(jié)果:

用到的重要函數(shù)是查找某個(gè)tag,獲取某個(gè)tag的下一個(gè)tag函數(shù):
find與find_all
函數(shù)定義如下:
def find(self, name=None, attrs={}, recursive=True, text=None,
**kwargs):
"""Look in the children of this PageElement and find the first
PageElement that matches the given criteria.
All find_* methods take a common set of arguments. See the online documentation for detailed explanations.
:param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param recursive: If this is True, find() will perform a recursive search of this PageElement's children. Otherwise, only the direct children will be considered. :param limit: Stop looking after finding this many results. :kwargs: A dictionary of filters on attribute values. :return: A PageElement.
:rtype: bs4.element.PageElement
"""
r = None
l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r
def find_all(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):
"""Look in the children of this PageElement and find all
PageElements that match the given criteria.
All find_* methods take a common set of arguments. See the online documentation for detailed explanations.
:param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param recursive: If this is True, find_all() will perform a recursive search of this PageElement's children. Otherwise, only the direct children will be considered. :param limit: Stop looking after finding this many results. :kwargs: A dictionary of filters on attribute values. :return: A ResultSet of PageElements.
:rtype: bs4.element.ResultSet
"""
generator = self.descendants
if not recursive:
generator = self.children
return self._find_all(name, attrs, text, limit, generator, **kwargs)
find 返回的是一個(gè)元素,find_all返回的是一個(gè)列表,舉例說明比較清晰。
允許傳入的參數(shù)包括:
1.字符串:tag的名稱,如h2, p, b, a等等分別表示查找<h2>, <p>, <b>, <a>等標(biāo)簽。 如:
soup.find_all('b')
# [<b>這里加粗</b>]
2.正則表達(dá)式
# 導(dǎo)入包
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
# 結(jié)果會找出 body, b等b開頭的標(biāo)簽
.3列表:與列表中任一元素匹配的內(nèi)容返回
soup.find_all(["a", "b"]) # 輸出: [<b>加粗</b>, # <a class="ddd" href="http://xxx" rel="external nofollow" >xxx</a> ]
4.True: 返回所有非字符串節(jié)點(diǎn)。
5.方法:傳入的方法接受唯一參數(shù):元素,并返回True或者False,若元素計(jì)算的值為True,則返回。
# 判斷一個(gè)tag有class屬性,但是沒有id屬性
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
# 使用方式
soup.find_all(has_class_but_no_id)
6.對元素指定判斷函數(shù):
# 查找所有href標(biāo)簽不是https的a標(biāo)簽
def not_https(href):
return href and not re.compile("https").search(href)
soup.find_all(href=not_https)
通過上述第5種和第6種方法,可以構(gòu)造很復(fù)雜的tag過濾函數(shù),從而實(shí)現(xiàn)過濾目的。
其他相關(guān)搜索函數(shù)如下:
find_next_sibling 返回后面的第一個(gè)同級tag節(jié)點(diǎn) find_previous_sibling 返回前面的第一個(gè)同級tag節(jié)點(diǎn) find_next 后面第一個(gè)tag節(jié)點(diǎn) find_previous 前面第一個(gè)tag節(jié)點(diǎn)
更多內(nèi)容可以在bs4官方文檔中查看。
到此這篇關(guān)于Python實(shí)現(xiàn)獲取網(wǎng)頁信息并解析的文章就介紹到這了,更多相關(guān)Python獲取網(wǎng)頁信息內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python django model聯(lián)合主鍵的例子
今天小編就為大家分享一篇python django model聯(lián)合主鍵的例子,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python求出0~100以內(nèi)的所有素?cái)?shù)
質(zhì)數(shù)又稱素?cái)?shù)。一個(gè)大于1的自然數(shù),除了1和它自身外,不能被其他自然數(shù)整除的數(shù)叫做質(zhì)數(shù);否則稱為合數(shù)。下面小編給大家?guī)砹薖ython求出0~100以內(nèi)的所有素?cái)?shù)實(shí)例代碼,需要的朋友參考下2018-01-01
淺談Pytorch torch.optim優(yōu)化器個(gè)性化的使用
今天小編就為大家分享一篇淺談Pytorch torch.optim優(yōu)化器個(gè)性化的使用,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python面向?qū)ο笾畠?nèi)置函數(shù)相關(guān)知識總結(jié)
本次要總結(jié)的的內(nèi)置函數(shù)共8個(gè),他們都跟面向?qū)ο蟮闹R相關(guān),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
Python3實(shí)現(xiàn)定時(shí)任務(wù)的四種方式
Python實(shí)現(xiàn)定點(diǎn)與定時(shí)任務(wù)方式比較多,找到下面四中實(shí)現(xiàn)方式,每個(gè)方式都有自己應(yīng)用場景;下面來快速介紹Python中常用的定時(shí)任務(wù)實(shí)現(xiàn)方式,一起看看吧2019-06-06
舉例詳解Python中threading模塊的幾個(gè)常用方法
這篇文章主要介紹了舉例詳解Python中threading模塊的幾個(gè)常用方法,threading模塊用來創(chuàng)建和操作線程,是Python學(xué)習(xí)當(dāng)中的重要知識,需要的朋友可以參考下2015-06-06
python并發(fā)編程多進(jìn)程 互斥鎖原理解析
這篇文章主要介紹了python并發(fā)編程多進(jìn)程 互斥鎖原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08

