写在前面:感谢马中华老师。
# 导入库
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()里的每个元素之间添加分隔符