Beautiful Soup 如何獲取到href


直接上代碼, 你需要修改一下黃色的部分。

from bs4 import BeautifulSoup
import requests

main(url):

html = requests.get(url, timeout=30) #獲取網頁
soup = BeautifulSoup(html, 'lxml') #獲取lxml樹
liTags = soup.find_all('li', attrs={'class': 'aaa'})#獲取li標簽,類名為aaa
comments = [] #初始化一個數組,存放每個li中需要保存的項
for li in liTags: # 迭代器獲取每個標簽的屬性值
  comment['href'] =li.find('a', attrs={'class': 'bbb'}, href = True).attrs['href']) #找到a標簽下,類名為bbb,屬性值
  comment['title'] =li.find('a', attrs={'class': 'bbb'}, href = True).attrs['title']) #找到a標簽下,類名為bbb,屬性值
  comment['text'] = li.find('span',attrs={'class':'ccc'}).text.strip() #獲取span標簽下,類名為ccc的文本

一般來說,網頁中li標簽下的內容,是我們想要的,所以:
1、把所有li標簽提取出來, li 可以通過class, id, name, title等等方式匹配。
2、迭代的方式,在每個里標簽下,把你想要的標簽下內容提取出來,除了class標簽,其他的所有標簽值都是可以提取出來的,包括title, id, name, ...

標簽下有用的內容,有兩種獲取方式:
.attrs 和 .text

需要注意的是,標簽匹配的時候,需要把空格去掉。例如: ' aaa'和'aaa'不是同樣的標簽,如果' aaa', 可能導致匹配不成功。
 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM