通过豆瓣网页源代码,了解python爬虫的一些基础知识;mocc网的一个例子
么有html经验的我,真是困难啊,这里边做边学html基础知识 http://www.runoob.com/tags/html-reference.html
主要有2个库:
requests: http://www.python-requests.org/en/master/
bs4: https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/
import requests
from bs4 import BeautifulSoup
import re
sum = 0
r = requests.get('https://book.douban.com/subject/26853356/comments/') #豆瓣小说 鱼王 短评界面
soup = BeautifulSoup(r.text, 'lxml')
pattern = soup.find_all('p', 'comment-content') # 看下面find_all的用法
for item in pattern:
print(item.string)
pattern_s = re.compile('<span class="user-stars allstar(.*?) rating"')#网页中评价分数匹配
p = re.findall(pattern_s, r.text) #返回列表
for star in p:
sum += int(star)
print("the average value is: {:.2f}".format(sum/len(p)))
一个经典的例子记录bs4中find_all的用法:
详见:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#find-all
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """
find_all( name , attrs , recursive , text , **kwargs )
find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件.
soup.find_all("title") #tag名称 # [<title>The Dormouse's story</title>] soup.find_all("p", "title") #css类名搜索 # [<p class="title"><b>The Dormouse's story</b></p>] soup.find_all("a") # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] soup.find_all(id="link2")# 按属性 值搜索 # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>] import re soup.find(text=re.compile("sisters")) # u'Once upon a time there were three little sisters; and their names were\n'
正则表达式用法
re.compile 函数
compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。
语法格式为:
re.compile(pattern[, flags])
findall
在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
findall(string[, pos[, endpos]])