#爬取内容选自一篇搜狐文章
import requests from bs4 import BeautifulSoup res = requests.get('http://www.sohu.com/a/226664758_153839') res.encoding = 'UTF-8' soup = BeautifulSoup(res.text, 'html.parser')
取出h1标签的文本:
for h1 in soup.find_all('h1'): print(h1.text)
取出a标签的链接:
for a in soup.find_all('a'): print(a.attrs.get('href'))
取出所有li标签的所有内容:
for li in soup.find_all('li'): print(li.contents)
取出一条新闻的标题、链接、发布时间、来源:
print(soup.select('div.article-info')[0].text) print(soup.select('div .text-title')[0].find('h1').text)