2 回答

TA貢獻(xiàn)1876條經(jīng)驗 獲得超6個贊
您的代碼中有大部分位,但只有一點點錯了。我認(rèn)為獲取標(biāo)題和鏈接的最簡單方法是使用以下內(nèi)容。
site = """<div>
<p class="title">
<a href="/news/123456">title_1</a>
</p>
</div>
<div>
<p class="title">
<a href="/news/789000">title_2</a>
</p>
</div>"""
s = BeautifulSoup(site, "html.parser")
for title in s.find_all('p', {'class':'title'}):
links = [x['href'] for x in title.find_all('a', href=True)]
line = title.get_text()
print(line)
print(links)
您可以看到 links 對象是一個列表,以防萬一每個標(biāo)題都有多個鏈接。

TA貢獻(xiàn)1803條經(jīng)驗 獲得超6個贊
嘗試這種方式將有助于從中查找所有值。
from bs4 import BeautifulSoup
text = """<div>
<p class="title">
<a href="/news/123456">title_1</a>
</p>
</div>
<div>
<p class="title">
<a href="/news/789000">title_2</a>
</p>
</div>
"""
soup = BeautifulSoup(text, 'html.parser')
for i in soup.find_all('p', attrs={'class': 'title'}):
link = None
if i.find('a'):
link = i.find('a').get('href')
print('Title:', i.get_text(strip=True), 'Link:', link)
# Output as:
# Title: title_1 Link: /news/123456
# Title: title_2 Link: /news/789000
添加回答
舉報