我正在嘗試從一些電子商務網站上抓取一些產品規格。所以我有一個各種產品的 URL 串列,我需要我的代碼去每個(這部分很容易)并刮出我需要的產品規格。我一直在嘗試使用 ParseHub——它適用于某些鏈接,但不適用于其他鏈接。例如,我的懷疑是,“輪徑”每次都會改變其位置,因此最終會獲取錯誤的規格值。
例如,HTML 中的其中一個部分如下所示:
<div class="product-detail product-detail-custom-field">
<span class="product-detail-key">Wheel Diameter</span>
<span data-product-custom-field="">8 Inches</span>
</div>
我想我能做的是如果我使用 BeautifulSoup 并且如果我能以某種方式使用 smth like
if soup.find("span", class_ = "product-detail-key").text.strip()=="Wheel Diameter":
*go to the next line and grab the string inside*
我該如何編碼?如果我的問題聽起來很愚蠢,我真的很抱歉,請原諒我的無知,我對網路抓取很陌生。
uj5u.com熱心網友回復:
您可以使用.find_next()功能:
from bs4 import BeautifulSoup
html_doc = """
<div >
<span >Wheel Diameter</span>
<span data-product-custom-field="">8 Inches</span>
</div>
"""
soup = BeautifulSoup(html_doc, "html.parser")
diameter = soup.find("span", text="Wheel Diameter").find_next("span").text
print(diameter)
印刷:
8 Inches
或者使用 CSS 選擇器 :
diameter = soup.select_one('.product-detail-key:-soup-contains("Wheel Diameter") *').text
uj5u.com熱心網友回復:
使用css selectors您可以簡單地鏈接/組合您的選擇以更加嚴格。在這種情況下,您選擇<span>包含您的字串并用于adjacent sibling combinator獲取下一個兄弟<span>。
diameter = soup.select_one('.product-detail-key:-soup-contains("Wheel Diameter") span').text
要么
diameter = soup.select_one('span.product-detail-key:-soup-contains("Wheel Diameter") span').text
注意:為避免AttributeError: 'NoneType' object has no attribute 'text',如果元素不可用,您可以在呼叫text方法之前檢查它是否存在:
diameter = e.text if (e := soup.select_one('.product-detail-key:-soup-contains("Wheel Diameter") span')) else None
例子
from bs4 import BeautifulSoup
html_doc = """
<div >
<span >Wheel Diameter</span>
<span data-product-custom-field="">8 Inches</span>
</div>
"""
soup = BeautifulSoup(html_doc, "html.parser")
diameter = e.text if (e := soup.select_one('.product-detail-key:-soup-contains("Wheel Diameter") span')) else None
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/428659.html
標籤:Python html 网页抓取 美丽的汤 解析集线器
