写在前面
前两天看了《python网络数据采集》这本书,大致看完了第一部分,第二部分不怎么看得进去,对于没有学过web的人来说学爬虫还是挺吃力地,很多时候只能照葫芦画瓢,现在的网站设计也越来越复杂了,最近VPN也不怎么灵,就打算拿一个国内的网站练练手。豆瓣这种新手难度就比较适合了。主要参考了另外一篇博客里的代码(链接在最后),但是那里使用python2写的,我用python3重写了一次,还是遇到了不少的坑的。
思路
关于库
在python3中,urlib2被改名为urllib,被分成一些子模块:urllib.request、urllib.parse、urlib.error,使用的时候只需import相应的函数就可以了。
另外一个很重要的库就是BeautifulSoup了,相信这个不用多说了,好用简单易上手。
关于如何抓取每本书的URL
https://book.douban.com/top250?start=0,这是豆瓣读书top250书单的首页,每页25本一共十页,具体每本书的url位置都很直观,其他很多博客里面也有详细介绍,我这里就不赘述了。我重点说说抓取url的方法,我看到的方法主要有以下几种:
- 正则表达式局部匹配,根据每个url所在区域的规律写相应的正则表达式,直接从html中匹配,个人觉得这种方法有点暴力,不是很优美。
- 其他的方法基本都可以归为这一类,就是利用BeautifulSoup来过滤抓取。方法还是挺多的,但是我在《python网络数据采集》这本书中看的是find_all()这个方法,但是看的博客中好像没有人用这种方法,我觉得这种方法不仅代码比较简单也很好了解,顺便还能用一下代码过滤文本的知识。
遇到的问题
- 文件写入的问题
我用的IDE是pycharm,然后文件保存最后还是用相对路径吧,python的文件输入输出还是比c友好很多的
在参考的代码中写入是这么的一段
if intro[0].get_text().encode('utf-8').find('展开全部')!=-1:
book_intro=intro[1]
if intro[2].get_text().encode('utf-8').find('展开全部')!=-1:
author_intro=intro[3]
else:
author_intro=intro[2]
这里只摘取了一小段,主要是判断书本的介绍有没有展开全部这个选项来抓取内容的。
问题在于这里的encode,不是很明白原来的博主为什么要这么写,可能是在python2下的规则吧。运行这里的时候提示错误,提示find需要的是str调用的,而get_text()函数返回的直接就是一个str对象,不需要encode。包括后面的写入文件,不需要特意的转换成utf-8再写入,直接将get_text()返回的值写入就可以了。
- 写入文件的时候遇到”illegal multibyte sequence”的问题
查阅了一下网上的资料,大体的说大概是写入中文的时候遇到的一个挺常见的问题?这里我也不是很清楚,欢迎大家在评论中指正。解决方法是在打开文件是加入“errors = ‘ignore’”这一参数。
打开文件的代码
with open(self.file_path + '\Top' + str(self.top_num) + '.txt', 'w', errors='ignore') as f:
- BeautifulSoup报警告”No module named requests, init.py:166: UserWarning: No parser was explicitly specified”
警告的大体意思是,你创建这个BeautifulSoup对象的时候怎么没给咱们显式的指定一个解析器啊,我给你安排了一个html解析器,问题不大,但是你拿到别的地方不一定能跑了啊。
行吧,那就给你安排一个html解析器吧。
book_bsObj = BeautifulSoup(book_html, "html.parser")
完整代码
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
import random
class DBTop250_Spider():
url = r"http://book.douban.com/top250?start="
page_num = 0
top_num = 1
headers = [
{'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0'},
{'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},
{
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 '
'Safari/535.11'},
{'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'},
{'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0'},
{
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu '
'Chromium/44.0.2403.89 Chrome/44.0.2403.89 Safari/537.36'}]
file_path = "..\Files\Books"
def Parse_Page(self):
req = Request(self.url+str(self.page_num * 25), headers=random.choice(self.headers))
page = urlopen(req).read()
bsObj = BeautifulSoup(page, "html.parser")
books_items = bsObj.find_all("a")
for item in books_items:
if 'title' in item.attrs:
self.Parse_Book(item.attrs['href'])
self.top_num += 1
self.page_num += 1
def Parse_Book(self, book_url):
print("book_url is: " + book_url)
try:
book_request = Request(book_url, headers=random.choice(self.headers))
book_html = urlopen(book_request).read()
book_bsObj = BeautifulSoup(book_html, "html.parser")
book_title = book_bsObj.h1
book_info = book_bsObj.find("div", {"id": "info"})
intro = book_bsObj.find_all("div", {"class": "intro"})
if intro[0].get_text().find("展开全部") != -1:
book_intro = intro[1]
if intro[2].get_text().find('展开全部') != -1:
author_intro = intro[3]
else:
author_intro = intro[2]
else:
book_intro = intro[0]
if intro[1].get_text().find('展开全部') != -1:
author_intro = intro[2]
else:
author_intro = intro[1]
with open(self.file_path + '\Top' + str(self.top_num) + '.txt', 'w', errors='ignore') as f:
f.write(book_title.get_text().strip() + '\n')
info_text = book_info.get_text().split(' ')
for info in info_text:
if info != '\n' and info != '':
f.write(info.strip())
f.write("\n\n内容简介: ")
f.write(book_intro.get_text())
f.write("\n\n作者简介: ")
f.write(author_intro.get_text())
except Exception as e:
if hasattr(e, "reason"):
print("Reason: " + e.reason)
sp = DBTop250_Spider()
for i in range(1, 11):
sp.Parse_Page()
抓取的数据
追风筝的人好看啊
参考资料
· 另一篇博客的源代码 https://github.com/wqlin/Spiders/blob/master/DBBooks/dbspider2.py#L18
彩蛋
吃完饭回来写这篇文章的时候想打开豆瓣读书,显示访问受限,虽然我已经用了随机请求头的方法,但是估计豆瓣那边已经判断我这边请求过多了吧,就是不知道会不会影响到校园网的其他人hhh