代码有可能出现以下错误:
'gbk' codec can't encode character u'\xa0' in position 3621: illegal multiby
网页编码问题,所学有限暂不能完全解决。 但实验发现利用 " gb2312" 不会出现以上问题,但是无法正常输出。
利用 " utf-8" 解码有可能会出现以上问题。
所实现的功能,爬取了糗事百科的文字类的段子,运行程序,点回车一次查看一个段子,输入Q退出程序。
整体的思路:
1. 写两个函数,一个 getonepage 抓取指定页码,该页的所有段子。一个QSBK_main 函数控制业务逻辑。
2. getonepage 首先利用 urllib 的 urlopen 方法抓取页面,然后用 beautifulsoup 的 find_all 方法提取我们所需要的作者和段子
这里作者和段子是分别提取的,然后利用 list 的 appned 方法合在了一起命名为 item ,也就是所一个段子是一个item .。然后将整 个页面的所有段子用一个 items[ ] 返回。
3.QSBK_main 这个很简单,新东西只有 get_text 方法,该方法是用来提取文字的。
相关的学习资料:http://cuiqingcai.com/990.html
环境:python + urllib +beautifulsoup
代码如下:
# -*- coding:utf-8 -*-
#import requests
from urllib import request
from bs4 import BeautifulSoup
import re
items = []
def geonepage(page):
print("开始获取,请等待少许.......")
url = 'http://www.qiushibaike.com/text/page/' + str(page)
req = request.Request(url)
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
response = request.urlopen(req).read()
response =response.decode('utf-8', errors = 'ignore')
soup = BeautifulSoup(response, 'html.parser')
count = 0
name_all = soup.find_all('h2')
item_all = soup.find_all('div', {'class':'content'})
for x in name_all:
item = name_all[count]
item.append(item_all[count])
items.append(item)
count += 1
print("获取完成,回车查看!")
return items
def QSBK_main():
enable = True
print("回车查看段子,输入Q离开页面。")
count_1 = 1
page = 1
while enable:
geonepage(page)
for story in items:
inp = input()
if inp == "Q":
enable = False
break
else:
print("第", page, "页","第", count_1, "个" )
print(story.get_text())
count_1 += 1
page += 1
count_1 = 1
QSBK_main()