1.采用beautifusoap获取网站信息:
import urllib. request
from bs4 import BeautifulSoup
from lxml import etree
html = 'http://www.000.com'
s=urllib.request.urlopen(html)
soap=BeautifulSoup(s,'lxml')
b=soap.div
sa=soap.find_all("div",id='u1')
soap1=BeautifulSoup(str(sa),'lxml')
for i in soap1.div:
print(i.string)
sb=soap.map.area['href']
print(sb)
s=urllib.request.urlopen('http:'+sb)
print(s.read().decode())
调试结果:获取百度网站的一些关键字:新闻、地图、视频等,并提取源图片的网站。
2.采用xpath获取网站信息:
import urllib.request
from bs4 import BeautifulSoup
from lxml import etree
html = 'http://www.000.com'
web= urllib.request.urlopen(html)
con=web.read()
s=etree.HTML(con,etree.HTMLParser())
s1=s.xpath('//*[@id="u1"]/a/text()')
s2=s.xpath('//map/area/@href')
print(s1)
print(s2)
调试结果:
['新闻', '000', '000', '视频', '00', '学术', '登录', '设置', '更多产品']
['//www.000.com/s?wd=%E4%BB%8A%E6%97%A5%E6%96%B0%E9%B2%9C%E4%BA%8B&tn=SE_PclogoS_8whnvm25&sa=ire_dl_gh_logo&rsv_dl=igh_logo_pcs']
爬虫实例:
import urllib.request from bs4 import BeautifulSoup import json http='http://www.0000.com/' reques=urllib.request.urlopen(http) list=[] data=reques.read() soap=BeautifulSoup(data,'html.parser') for j in soap.find_all(class_='mulu'): s=j.find('h2')#各书籍的大标题 list1 = [] if s!=None: for i in j.find_all('a'):#小标题 name = i.string href = i.get('href') time = i.get('title') list1.append({'name': name, 'href': href, 'time': time}) list.append({s.string: list1}) file=open('exam.json','w',encoding='utf-8') jsondata=json.dump(list,file,ensure_ascii=False,indent=4)#将抓取的数据写入文件 file1=open('exam.json','r',encoding='utf-8') data2=json.load(file1)#读出数据 for i in data2: print(i)
调试结果:由于数据太大,只展示开头的数据。
{'盗墓笔记1七星鲁王宫': [{'name': '七星鲁王 第一章 血尸', 'href': 'http://0000.com/biji1/1.html', 'time': '[2012-5-19 3:3:52] 七星鲁王 第一章 血尸'},