用re库正则方法抓取名言网数据

写在前面:感谢马中华老师。

# 导入库
from urllib.request import urlopen
import re

# 模拟浏览器发起请求
url = 'http://quotes.toscrape.com/'
# 第二页
# url = 'http://quotes.toscrape.com/page/2/'
# url = 'http://quotes.toscrape.com/page/3/'
response = urlopen(url)

# 获取网页内容
html_content = response.read().decode("utf-8")

# 用正则给网页内容分组
# 注意:.*只能匹配除换行符以外的所有内容(因此含有换行符的网页标签则无法匹配,如名言tag对应的网页代码:div标签)
pattern = '<span class="text" itemprop="text">(.*)</span>'

# 抓取名言
quotes10_span = re.findall(pattern, html_content)

# 抓取作者
authors10_small = re.findall('<small class="author" itemprop="author">(.*)</small>', html_content)

# 抓取标签
# tags = re.findall('<a class="tag" href=".*">.*</a>', html_content)
# tags10_meta = re.findall('<meta class="keywords" itemprop="keywords" content="(.*)">', html_content)  //(meta标签不能被提取)
# div10 = re.findall('<div class="tags">(.*)</div>', html_content)   //.在python的正则中不能匹配换行符,需要匹配换行的话需要如下

# div10 = re.findall('<div class="tags">.*</div>', html_content, re.RegexFlag.DOTALL)   #RegexFlag.DOTALL大小写严格匹配
# print(div10)    //查看div10
# print(len(div10))    //查看div10列表中元素数量,结果为1.解决:加入?,屏蔽贪婪规则👇

div10 = re.findall('<div class="tags">.*?</div>', html_content, re.RegexFlag.DOTALL)   # RegexFlag.DOTALL大小写严格匹配
# print(len(div10))    //再次查看div10列表中元素数量,结果为10

# 每个元素,就是每句名言的所有标签
tag10 = []
# 每循环一次,处理一句名言的标签
for div in div10:
    # 存储每一句话的所有标签
    tags_each_quote = []
    a_tags= re.findall('<a class="tag" href=".*">(.*)</a>', div)
    for tag in a_tags:
        tags_each_quote.append(tag)  # .append用于向对象添加元素
    # 打印输出每一句话的标签
    # print(tags_each_quote)
    tag10.append(tags_each_quote)
# 处理结果
# print(len(quotes10_span))  //检查名言列表元素数量
# for quotoe in quotes10_span:
#     print(quotoe)   //输出每一条名言
#
# print(len(authors10_small))   //检查作者列表元素数量
# for author in authors10_small:
#     print(author)     //输出每一位作者
for i in range(10):
    print(quotes10_span[i].strip("“”"), authors10_small[i], ",".join(tag10[i]), sep="\t\t\t")
    # .strip()用于去除元素最左边或最右边的字符
    # sep=""用于给print()里的每个元素之间添加分隔符
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值