一直用的是python3.4版本,所以只用了urllib爬数据,然后使用BeautifulSoup做为分析。
1、首先安装BeautifulSoup,执行命令如下:
pip install BeautifulSoup4
2、第二步开始写代码,就以我的博客为例,其实代码很简单
from urllib import request
from bs4 import BeautifulSoup
fp = request.urlopen("http://www.cnblogs.com/youyuan1980/")
html = fp.read()
soup = BeautifulSoup(html, 'html.parser')
for div in soup.find_all('a',attrs={"class":"postTitle2"}):
print(div.get('href')) #显示a标签属性的href
print('text:'+div.get_text()) #显示a标签里面的text
不用解释,看看就明白了。
重新整理了一下,最终的代码如下:
from urllib import request
from bs4 import BeautifulSoup
def GetHtml(url):
fp = request.urlopen(url)
return fp.read()
def GetParser(url):
html = GetHtml(url)
return BeautifulSoup(html, 'html.parser')
if __name__ == '__main__':
url = "http://www.cnblogs.com/youyuan1980/"
titleParser = GetParser(url)
for titlediv in titleParser.find_all('a',attrs={"class":"postTitle2"}):
titleurl = titlediv.get('href')
titletext = titlediv.get_text()
infoParser = GetParser(titleurl)
infotext = infoParser.find('div',attrs={"id":"cnblogs_post_body"})
print(titletext)
print(infotext)
一些改进,可以用requests库,不要求很严格的发问下,可以这么做,使用方法如下
import requests fp = requests.get(url) print(fp.text)
替换掉urllib感觉更方便。