![](/img/trans.png)
[英]How Can I Get Information From An A Tag Between Two Span Tags in BeautifulSoup Using Python?
[英]How can I get information from an <a href> tag within <div> tags with BeautifulSoup and Python?
全部。 我有一個關於使用 Python 的 BeautifulSoup 的快速問題。 我有幾段 HTML 看起來像這樣(唯一的區別是鏈接和產品名稱),我正在嘗試從“href”屬性中獲取鏈接。
<div id="productListing1" xmlns:dew="urn:Microsoft.Search.Response.Document">
<span id="rank" style="display:none;">94.36</span>
<div class="productPhoto">
<img src="/assets/images/ocpimages/87684/00131cl.gif" height="82" width="82" />
</div>
<div class="productName">
<a class="on" href="/Products/ProductInfoDisplay.aspx?SiteId=1&Product=8768400131">CAPRI SUN - JUICE DRINK - COOLERS VARIETY PACK 6 OZ</a>
</div>
<div class="size">40 CT</div>
我目前有這個 Python 代碼:
productLinks = soup.findAll('a', attrs={'class' : 'on'})
for link in productLinks:
print link['href']
這有效(對於頁面上的每個鏈接,我都會得到類似/Products/ProductInfoDisplay.aspx?SiteId=1&Product=8768400131
); 但是,我一直在嘗試弄清楚是否有辦法在“href”屬性中獲取鏈接,而無需明確搜索“class =“on””。 我想我的第一個問題應該是這是否是查找此信息的最佳方式(盡管我的 CSS 和 HTML 技能不是很好,但 class="on" 似乎太籠統並且將來可能會中斷)。 我已經嘗試了多種 find、findAll、findAllnext 等方法的組合,但我無法讓它發揮作用。 這主要是我所擁有的(我重新排列並更改了很多次):
productLinks = soup.find('div', attrs={'class' : 'productName'}).find('a', href=True)
如果這不是一個好方法,我怎樣才能從<div class="productName">
標簽到達<a>
標簽? 如果您需要更多信息,請與我們聯系。
謝謝你。
好吧,一旦有了<div>
元素,就可以通過調用find()
來獲取<a>
子元素:
productDivs = soup.findAll('div', attrs={'class' : 'productName'})
for div in productDivs:
print div.find('a')['href']
但是,由於<a>
就在<div>
之上,您可以從 div 中獲取a
屬性:
productDivs = soup.findAll('div', attrs={'class' : 'productName'})
for div in productDivs:
print div.a['href']
現在,如果你想把所有的<a>
元素放在一個列表中,你上面的代碼將不起作用,因為find()
只返回一個與其條件匹配的元素。 您將獲取 div 列表並從中獲取子元素,例如,使用列表推導式:
productLinks = [div.a for div in
soup.findAll('div', attrs={'class' : 'productName'})]
for link in productLinks:
print link['href']
我在 BeautifulSoup4 中給出了這個解決方案
for data in soup.find_all('div', class_='productName'):
for a in data.find_all('a'):
print(a.get('href')) #for getting link
print(a.text) #for getting text between the link
data = soup.find_all('div', class_='productName') a_class = data[0].find_all('a') url_ = a_class[0].get('href') print(url_)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.