04、博客文章

    题目要求:你需要爬取的是博客人人都是蜘蛛侠,首页的四篇文章信息,并且打印提取到的信息。
 
    提取每篇文章的:文章标题、发布时间、文章链接
 
    网页URL:https://spidermen.cn/
 
 1 #4、博客文章
 2 #    题目要求:你需要爬取的是博客人人都是蜘蛛侠,首页的四篇文章信息,并且打印提取到的信息。
 3 #    提取每篇文章的:文章标题、发布时间、文章链接
 4 #    网页URL:https://spidermen.cn/
 5 
 6 import requests
 7 from bs4 import BeautifulSoup
 8 res = requests.get('https://spidermen.cn/')
 9 html = res.text
10 soup = BeautifulSoup(html,'html.parser')
11 items = soup.find_all('header',class_='entry-header')
12 for item in items:
13     print(item.find('h2').text,end='	')
14     print(item.find('time',class_='entry-date published')['datetime'],end='	')
15     print(item.find('a')['href'],end='
')
16 
17 
18 '''
19 执行结果如下:
20 未来已来(四)——Python学习进阶图谱    2018-12-18T11:17:37+00:00       https://wordpress-edu-3autumn.localprod.forc.work/all-about-the-future_04/
21 未来已来(三)——同九义何汝秀  2018-12-18T11:12:02+00:00       https://wordpress-edu-3autumn.localprod.forc.work/all-about-the-future_03/
22 未来已来(二)——拥抱AI        2018-12-18T10:50:33+00:00       https://wordpress-edu-3autumn.localprod.forc.work/all-about-the-future_02/
23 未来已来(一)——技术变革      2018-12-18T10:23:16+00:00       https://wordpress-edu-3autumn.localprod.forc.work/all-about-the-future_01/
24 '''
25 
26 
27 '''
28 老师代码
29 
30 import requests
31 from bs4 import BeautifulSoup
32 
33 url_destnation = 'https://spidermen.cn/';
34 res_destnation = requests.get (url_destnation)
35 # 打印响应码
36 print(res_destnation.status_code)
37 
38 bs_articles = BeautifulSoup(res_destnation.text,'html.parser')
39 # 首先找到每篇文章所在的相同的元素
40 list_articles = bs_articles.find_all('header', class_ = "entry-header")
41 for tag_article in list_articles: # 遍历列表
42     tag_title = tag_article.find('h2',class_ = "entry-title") # 找文章标题
43     tag_url = tag_article.find('a',rel = "bookmark")  # 找文章链接
44     tag_date = tag_article.find('time',class_="entry-date published") # 找文章发布时间
45     print(tag_title.text,'发布于:',tag_date.text) # 打印文章标题与发布时间
46     print(tag_url['href'])  # 换行打印文章链接,需要使用属性名提取属性值
47 '''
items中每个Tag的内容如下
 
 1 <header class="entry-header">
 2     <div class="entry-meta">
 3         <span class="screen-reader-text">发布于</span>
 4             <a href="https://wordpress-edu-3autumn.localprod.forc.work/all-about-the-future_04/" rel="bookmark">
 5                 <time class="entry-date published" datetime="2018-12-18T11:17:37+00:00">2018-12-18</time>
 6                 <time class="updated" datetime="2018-12-18T11:25:15+00:00">2018-12-18</time>
 7             </a>
 8     </div>
 9     <!-- .entry-meta
10         -->
11     <h2 class="entry-title"><a href="https://wordpress-edu-3autumn.localprod.forc.work/all-about-the-future_04/"
12             rel="bookmark">未来已来(四)——Python学习进阶图谱</a></h2>
13 </header>
 
原文地址:https://www.cnblogs.com/www1707/p/10692324.html