需要一个chrome浏览器插件,https://chrome.google.com/webstore/detail/infolite/ipjbadabbpedegielkhgpiekdlmfpgal,安装好后打开,可以看到网页块域的类名称
import requestsfrom bs4 import BeautifulSoupres = requests.get('http://news.sina.com.cn/china/')res.encoding = 'utf-8'soup = BeautifulSoup(res.text,'html.parser')for news in soup.select('.news-item'): if len(news.select('h2')) > 0: time = news.select('.time')[0].text h2 = news.select('h2')[0].text a = news.select('a')[0]['href'] print(time,h2,a)结果: