网络爬虫基础练习

练习:

 这是练习的HTML文件:net.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>这是标题!</title>
</head>
<body>
    <h1>这是h1标签</h1>
    <P ID = "p1Node">This is paragraph 1.</P>
    <P ID = "p2Node">段落2</P>
    <li><a href="http://www.gzcc.cn/">广州商学院</a></li>
    <li><a href="http://news.gzcc.cn">第一新闻网</a></li>
    <li><a href="http://news.gzcc.cn">第二新闻网</a></li>
    <li>
                <a href="http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0327/9106.html">
                    <div class="news-list-thumb"><img src="http://oa.gzcc.cn/uploadfile/2018/0327/20180327035432412.jpg"></div>
                    <div class="news-list-text">
                        <div class="news-list-title" style="">新西兰梅西大学代表团来我校访问</div>
                        <div class="news-list-description">3月27日上午,新西兰梅西大学商务发展与运营经理Rebecca Argyle、商务经理Joy Hotter等一行来我校访问交流。</div>
                        <div class="news-list-info"><span><i class="fa fa-clock-o"></i>2018-03-27</span><span><i class="fa fa-building-o"></i>外国语学院</span></div>
                    </div>
                </a>
    </li>

</body>
</html>

取出h1标签的文本

取出a标签的链接
取出所有li标签的所有内容
取出第2个li标签的a标签的第3个div标签的属性

取出一条新闻的标题、链接、发布时间、来源

# -*- coding:UTF-8 -*-
# -*- author:deng -*-
import requests
from bs4 import BeautifulSoup
res = requests.get('http://localhost:63342/hello/net.html?_ijt=tuenh08pgsh6msjqkka9cjg3im')
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)
# 取出第2个li标签的a标签的第3个div标签的属性
print(soup.find_all('li')[1].a.find_all('div')[2].attrs)

# 取出一条新闻的标题、链接、发布时间、来源
print(soup.select('div .news-list-title')[0].text)
print(soup.select('div .news-list-thumb')[0].parent.attrs.get('href'))
print(soup.select('div .news-list-info > span')[0].text)
print(soup.select('div .news-list-info > span')[1].text)

问题:每次requests获取新建的HTML文件时,都要重新用浏览器打开net.html来更新localhost地址才能运行Python文件。

原文地址:https://www.cnblogs.com/dfq621/p/8672206.html