直接上代碼, 你需要修改一下黃色的部分。
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', 可能導致匹配不成功。