爬虫第二战,beautifulsoup小例
2016-12-14 19:37
309 查看
额。。这个标题着实难到我这个英文很烂的人了,毕竟在验证bs的时候有着四个单词写错俩的战绩
,不过想要真的成为一只程序熊,阴雨(英语)很烂可是不行的。进入正题。
如果有在bs安装的时候遇见问题的小伙伴可以去看之前的博客,虽然很烂,,只希望能稍微帮上一丢丢。bs在某些方面是要优于正则的,比如它是通过标签对问题进行获取分析的,直观上看起来会比较简单,但,有些时候单靠bs是获取不到有些内容的佐以正则效果更佳。今天要写的内容是用bs爬有妖气上面的漫画的名字、作者、类型等内容,就像这样
我们的套路是不会变的,等会。。忘发链接了:点击打开链接http://www.u17.com/comic_list/th99_gr99_ca99_ss1_ob0_ac0_as0_wm0_co99_ct99_p1.html
贼尴尬,那么进入下一步,分析网页源代码
我们要爬的就是那些被圈出来部分,上代码
#coding:utf-8
import bs4
import re
import time
import urllib
from bs4 import BeautifulSoup
l = open('manhua0.txt','a+')
def getHtml():
for i in range(1,3) : # 爬取两页
url = 'http://www.u17.com/comic_list/th99_gr99_ca99_ss1_ob0_ac0_as0_wm0_co99_ct99_p%d.html' % i
page = urllib.urlopen(url)
html = page.read()
time.sleep(1)
soup = BeautifulSoup(html,'html.parser') # 调用bs
lis = soup.find_all('div',class_='info')
fi=[] # 创建一个空列表,方便存入数据
for content in lis:
work =[]
b = content.select('h3') # 在h3标签下获取更新时间 作者名
for item in b:
work.append(item.get_text('\t',strip=True))
d = content.find('a').get_text() # 在a 标签下获取作品名
work.append(d) # 存入列表
work.append('\n')
a = content.find('p').get_text() # 获取月票数收藏量
work.append(a)
work.append('\n')
e = content.find('p',class_="text").get_text() # 获取简介
work.append(e)
work.append('\n')
fi.append(work)
for p in fi:
for jieguo in p:
l.write(jieguo.encode(encoding='utf-8')) # 将列表内容写入文本
return html
getHtml()
代码功能请看注释,谢谢。
由于是很久以前写的,感觉炒鸡麻烦,便在写博客的时候看了看有没有简单一点的写法,我去,,果然有,那么,翠花,把我代码呈上来,,不是盛好了端上来
#coding:utf-8
import bs4
import re
import time
import urllib
from bs4 import BeautifulSoup
l = open('manhua0.txt','a+')
for i in range(1,3) :
url = 'http://www.u17.com/comic_list/th99_gr99_ca99_ss1_ob0_ac0_as0_wm0_co99_ct99_p1.html'
page = urllib.urlopen(url)
html = page.read()
time.sleep(1)
soup = BeautifulSoup(html,'html.parser')
a = soup.find_all('ul') #大概需要注释的只有这条,我发现<ul>标签下囊括所有所需的内容,但我们所需要的不是位于首位那个便需要取出所有
l.write(a[6].get_text('\n',strip=True).encode('utf-8')) #找到对应的<ul>,获取文本,去空格 ,加换行就好了
l.close()
有没有感觉更加明朗也简单了些。代码功能请看注释
欢迎各位大神批评指点,欢迎小伙伴们砸臭鸡蛋、烂菜叶子神马的。。。我去,,真砸啊!
THANKS
相关文章推荐
- 一个简单的不用cookie的人人网状态爬取的python爬虫,使用beautifulsoup
- Python爬虫包 BeautifulSoup 学习(七) children等应用
- python爬虫系列(六):强大的beautifulsoup
- Python使用BeautifulSoup爬虫,和pyspider框架的使用
- Python爬虫包BeautifulSoup学习实例(五)
- Python3.7 爬虫(二)使用 Urllib2 与 BeautifulSoup4 抓取解析网页
- 简单爬虫python实现02——BeautifulSoup的使用
- Python爬虫:用BeautifulSoup进行NBA数据爬取
- 网页爬虫工具BeautifulSoup使用总结
- Python爬虫实例——基于BeautifulSoup和requests实现
- Python爬虫常用模块,BeautifulSoup笔记
- Python爬虫实例(3)-用BeautifulSoup爬取多个可翻页网页上的多张照片
- Python3 BeautifulSoup爬虫 HDU自动提交
- Python爬虫urllib笔记(四)之使用BeautifulSoup爬取百度贴吧
- python-爬虫-beautifulsoup
- Python-利用beautifulsoup写个豆瓣热门图书爬虫
- 使用BeautifulSoup实现简单豆瓣爬虫
- 爬虫的基本概念及BeautifulSoup的基本使用
- 爬虫基本库之beautifulsoup
- [置顶] python爬虫还在用BeautifulSoup?你有更好的选择!